Skip to content

Model.scope ambiguous columns #3756

@joshuadmatthews

Description

@joshuadmatthews

This is a copy of issues #3123 which seems to not be fixed unless I am missing some new configuration to resolve it... I believe it was supposed to be fixed in the scope refactor.

When a model has a scope that contains a where, it will cause all columns referencing that model in the SQL's where clause to be referenced without being prefixed by their table reference. If including an association that also has a column with the name referenced in the where clause, and the query does not subquery for the source model, the query will error due to ambiguous column names.

Example

Here's an example model definition.

var Foo = sequelize.define('Foo', {
status: DataTypes.STRING
}, {
defaultScope: { where: { status: 'active' } }
});

var Bar = sequelize.define('Bar');

Foo.hasMany(Bar);
Bar.belongsTo(Foo);

Here, we query for a specific Foo instance by id, which will cause Sequelize to generate a query that does not use a subquery to retrieve Foo, allowing the where conditions to break out into the main query.

Foo.find({
where: { id: 1 } // This causes the source model (Foo) to not be retrieved via subquery
include: Bar
});
The generated SQL's FROM will be Foo, it will JOIN Bar, and then the where clause will look something like

WHERE id = 1 AND status = 'active'

And this will result in the error Ambiguous column name 'id'.

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