Skip to content

Eager loading for multiple associations / associated models not working as expected #7345

@pimvanderheijden

Description

@pimvanderheijden

I am very enthusiastic about sequelize and use it as an ORM for Postgres. I want to achieve the following but keep having trouble to apply the explanations and examples in the docs. There seems to be a weird quirk in eager loading two models. What is wrong?

Listing.findAndCountAll({
    where: query ? query : {},
    offset: offset ? offset : 0,
    limit: limit ? limit : 100,
    attributes: ['price', 'description', 'zipcode', 'lng', 'lat'],
    include: [{
        model: Category,
        attributes: ['name', 'image']
      } , {
        model: User,
        as: 'Owner',
        attributes: ['firstName', 'rating', 'avatar']
      }]
})

When I try to do this I get Listing.OwnerId does not exist. However, when I remove Category from the include statement, the whole thing works as I expect:

include: [{
        model: User,
        as: 'Owner',
        attributes: ['firstName', 'rating', 'avatar']
}]

It also works for including categories only. What is going on here? I found it very confusing.

Associations are as follows:

        Listing.belongsTo(models['User'], { as: 'Owner' })
        Listing.belongsToMany(models['Category'], { through: 'ListingsCategories' })
        Category.belongsToMany(models['Listing'], { through: 'ListingsCategories' })

Also I found that the option raw: true messes with the include, the eager loading. In my case it results in one listing for each association. So let's say I have 3 listings and those are all three associated to 2 different Categories I received 6 listings with listing.category: category instead of 3 listings with a categories array like listing.categories: [one_category, other_category]. Removing the raw option solved this. Why?

Thanks in advance

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions