Repository navigation
Description
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
[-]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[/+]mikealche commentedon Feb 6, 2018
I'm also seeing this happen.
I have two models
Events and 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)
which was working completely fine until I added a default scope for events:
This broke completely the above user query
I think this is related to this issue
behcet commentedon May 7, 2018
leaving a comment
stephenheard commentedon May 30, 2018
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.
stephenheard commentedon May 30, 2018
...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.
mattdiamond commentedon Jun 4, 2018
Revisiting this bug, I noticed that my example defines the
foreignKeyproperty 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 theforeignKeystring should match the casing of the model property, not the database field. (Sequelize uses theforeignKeystring to access the model property, and it will grab the appropriatefieldvalue from there.) So in this case,foreignKeyshould have been set tosecretClubId. Not sure if that would fix the issue, but it's worth pointing out.markhealey commentedon Sep 7, 2018
I have the same issue where we have a
Usermodel that has an associationUser.belongsTo(Team).When we add a
defaultScopetoUserwithattributes: { exclude: ["password"] }, the automatically generatedteamIdFK attribute is NOT included in the query.Setting the foreign key like
User.belongsTo(Team, { foreignKey: "teamId" })does not fix it, fyi @mattdiamond.mattdiamond commentedon Dec 6, 2018
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.
4 remaining items
sushantdhiman commentedon Mar 29, 2019
Has anyone tested this against v5?
dsbert commentedon Mar 29, 2019
@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.
nicolasadamini commentedon May 7, 2019
Hi, just passing by to say I also had the issue:
https://stackoverflow.com/questions/56000198/cannot-increment-with-sequelize-column-0-of-relation-users-does-not-exists/56029525#56029525
Sequelize 4.42.0papb commentedon Jul 29, 2019
Hello! Can you please open a separate issue for this?