P
P
Pavel2019-07-22 12:56:21
Node.js
Pavel, 2019-07-22 12:56:21

How to do 1:n eager loading in Sequelize?

Hello. Trying to implement a 1:n relationship in sequelize.
Made according to the example docs.sequelizejs.com/manual/associations.html#1-n ,

Comment.belongsTo(models.Post, {
            foreignKey: 'commentableId',
            constraints: false,
            as: 'post'
        });

        Comment.belongsTo(models.Event, {
            foreignKey: 'commentableId',
            constraints: false,
            as: 'event'
        });

but I can’t find in the documentation how to make eager loading of relations through include. That is, I want to get a list of comments and a record for which each is made for the admin panel. With lazy loading, everything is clear, we write .getPost() or .getEvent() after we get the comment from the database and see the value of the "commentable" column. But I don’t understand how to make a greedy one .. how to write include correctly, or at least manually add join.
let comments = await queryComments.findAll({
                include: [
                    {
                        as: "authorData",
                        model: models.User,
                        attributes: ['id', 'name']
                    },
                    {
                        association:  '', //как сюда подставить правильную ассоциацию? Полагаю, this.commentable работать не будет никак
                    }
                ],
                attributes: ['id','author','createdAt','parentId','commentable','commentableId'],
                ...pagination.pagesQuery
            });

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question