Skip to content

Scopes defined with an attributes object may break if associations are registered after scope creation #8612

Open

Description

@mattdiamond

What are you doing?

From what I've seen in the source code, creating an association (like belongsTo) will add the relevant foreign keys to the model's rawAttributes object in the injectAttributes function. When a scope is created, this same object is used in the _expandAttributes function to populate the scope's attributes (if an attributes object is present).

If, however, a scope with attributes is created before the association, the scope's attributes object will not be populated with those foreign keys. Normally this is fine, but will break things if Sequelize uses the subquery strategy (which it defaults to when there is a query limit and a multi-association). The problem is that these foreign keys do not appear in the subquery table (which is generated using the query attributes), so the joins later in the query are unable to find them if there is a difference between the foreign key field name and the model property (e.g. one is camelCase and one is underscored).

A basic example:

const Item = sequelize.define('Item', { ... });
const SecretClub = sequelize.define('SecretClub', { ... });

const User = sequelize.define('User', {
  id: {
    type: DataTypes.INTEGER,
    autoIncrement: true,
    primaryKey: true
  },
  password: {
    type: DataTypes.STRING,
  },
  secretClubId: {
    type: DataTypes.INTEGER,
    field: 'secret_club_id'
  }
}, {
  scopes: {
    withItems: {
      attributes: { exclude: ['password'] },
      include: [
        { model: SecretClub, as: 'secretClub' },
        { model: Item, as: 'items' }
      ]
    }
  }
});

User.hasMany(Item, { as: 'items' });
User.belongsTo(SecretClub, { as: 'secretClub', foreignKey: 'secret_club_id' });

User.scope('withItems').findOne().then(result => console.log(result));

What do you expect to happen?

Sequelize should output a user along with the associated models.

What is actually happening?

A SQL error along the lines of column User.secret_club_id does not exist. This is because the secret_club_id join was performed against a subquery table that aliased the field name to secretClubId and provided no underscored version. If the scope had been created after the association, the underscored foreign key would have been included in the scope's attributes, and would therefore have been present in the subquery, avoiding the error.

One potential fix would be to delay expanding a scope's attributes until the scope is actually used (perhaps by moving the _conformOptions call to the top of _injectScope). This would ensure that the attributes reflect the most up-to-date version of the model. The current strategy of expanding attributes on scope creation means that the scope is locked to a specific state of the model, leaving scoped queries vulnerable to bugs such as this one.

Dialect: postgres
Sequelize version: 3.x
Tested with master branch: No

Activity

  1. changed the title [-]Scopes defined with an attributes object may break if associations are registered after model/scope initialization[/-] [+]Scopes defined with an attributes object may break if associations are registered after scope creation[/+] on Nov 9, 2017
  2. mikealche commented on Feb 6, 2018

    @mikealche

    I'm also seeing this happen.

    I have two models
    Events and User

    
    db.User.hasMany(db.Event, { onDelete: 'CASCADE' })
    db.Event.belongsTo(db.User)
    
    

    and was using this method for getting the user info (which also gets the users events, the tickets of that event, and the other users that hold that ticket)

    User.find({
        where: {
          _id: userId
        }
        ,
        attributes: [
          '_id',
          'name',
          'email',
          'role',
          'provider'   
          ],
        include: [{ model: Event, include: [Place, 
    { model: Ticket, include: [{ model: User , attributes: ['name', 'photoUrl'] }] }] },{model: Media, as:'profile_picture'}]
    

    which was working completely fine until I added a default scope for events:

    defaultScope: {
            where: {
              status: 'active'
            }
        },
    

    This broke completely the above user query

    I think this is related to this issue

  3. behcet commented on May 7, 2018

    @behcet

    leaving a comment

  4. stephenheard commented on May 30, 2018

    @stephenheard

    I'm seeing this behavior as well (I'm using sequelize 4). Workaround is to manually add the foreign keys to be included with the default scope.

  5. stephenheard commented on May 30, 2018

    @stephenheard

    ...or simply manually define the primary key columns in your model definition instead of letting the association definition do it for you. This is going to be my preferred way to address this behavior.

  6. mattdiamond commented on Jun 4, 2018

    @mattdiamond
    Author

    Revisiting this bug, I noticed that my example defines the foreignKey property of the User's SecretClub association using the underscored column name (secret_club_id). One thing I've learned (that the Sequelize docs don't exactly make clear) is that the foreignKey string should match the casing of the model property, not the database field. (Sequelize uses the foreignKey string to access the model property, and it will grab the appropriate field value from there.) So in this case, foreignKey should have been set to secretClubId. Not sure if that would fix the issue, but it's worth pointing out.

  7. markhealey commented on Sep 7, 2018

    @markhealey

    I have the same issue where we have a User model that has an association User.belongsTo(Team).

    When we add a defaultScope to User with attributes: { exclude: ["password"] }, the automatically generated teamId FK attribute is NOT included in the query.

    Setting the foreign key like User.belongsTo(Team, { foreignKey: "teamId" }) does not fix it, fyi @mattdiamond.

  8. mattdiamond commented on Dec 6, 2018

    @mattdiamond
    Author

    This still seems to be an issue.

    @markhealey Did you ever figure the issue out in your case? If you were adding the association after creating the scope, that might be the problem: the scope is constructed without including the foreign key, and adding the association doesn't modify the previously created scope.

  9. 4 remaining items

  10. sushantdhiman commented on Mar 29, 2019

    @sushantdhiman
    Contributor

    Has anyone tested this against v5?

  11. deleted a comment from stale on Mar 29, 2019
  12. deleted a comment from stale on Mar 29, 2019
  13. deleted a comment from stale on Mar 29, 2019
  14. deleted a comment from stale on Mar 29, 2019
  15. dsbert commented on Mar 29, 2019

    @dsbert

    @sushantdhiman In v5, I am experiencing an issue which sounds like it is the same or closely related. When including a model with a default scope, the query is generated with the aliased field names instead of the original column names. Removing the default scope fixes the issue.

  16. papb commented on Jul 29, 2019

    @papb
    Member

    @sushantdhiman In v5, I am experiencing an issue which sounds like it is the same or closely related. When including a model with a default scope, the query is generated with the aliased field names instead of the original column names. Removing the default scope fixes the issue.

    Hello! Can you please open a separate issue for this?

  17. added
    type: bug
    and removed on Jul 29, 2019
  18. added theissue type on Mar 9, 2025
  19. removed
    type: bug
    on Mar 9, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions