sequelize icon indicating copy to clipboard operation
sequelize copied to clipboard

When eager-loading WHERE params must be prefixed with table name

Open emirotin opened this issue 13 years ago • 4 comments

Example: there're User and Ad models. Both have id column. Ad.belongsTo(User).

Doing Ad.find({ where: 14, include: [ User] }) runs this query on Postgres:

SELECT "Ads".*, "Users"."firstName" AS "Users.firstName", "Users"."lastName" AS "Users.lastName", "Users"."displayName" AS "Users.displayName", "Users"."email" AS "Users.email", "Users"."id" AS "Users.id", "Users"."createdAt" AS "Users.createdAt", "Users"."updatedAt" AS "Users.updatedAt" FROM "Ads" LEFT OUTER JOIN "Users" AS "Users" ON "Users"."id" = "Ads"."UserId" WHERE "id"=14;

The id here is ambiguous and leads to an error.

The proper query is

SELECT "Ads"., "Users"."firstName" AS "Users.firstName", "Users"."lastName" AS "Users.lastName", "Users"."displayName" AS "Users.displayName", "Users"."email" AS "Users.email", "Users"."id" AS "Users.id", "Users"."createdAt" AS "Users.createdAt", "Users"."updatedAt" AS "Users.updatedAt" FROM "Ads" LEFT OUTER JOIN "Users" AS "Users" ON "Users"."id" = "Ads"."UserId" WHERE *"Ads"."id"=14**;

Obviously this will happen not only with id but with any attribute name present on both models (but id is most frequent cause that's what happens when I want to fetch a single instance with associated data.

The issue is kind of major.

emirotin avatar May 18 '13 12:05 emirotin

Yesterday I had the same problem when I did an "include". The MySQL QueryGenerator doesn't have that problem because it prepends the table names on attributes in the where clause when doing a "select". I fixed that by copying some of the code from the MySQL QueryGenerator to the Postgres QueryGenerator.

pbraun avatar May 18 '13 16:05 pbraun

I'll create a pull request for it very soon.

pbraun avatar May 18 '13 16:05 pbraun

great I confirm that it solves my issue

emirotin avatar May 18 '13 16:05 emirotin

Closed by #630

janmeier avatar May 19 '13 15:05 janmeier