examples icon indicating copy to clipboard operation
examples copied to clipboard

fix-sequelize-ts: SequelizeDatabaseError: Column 'id' in field list is ambiguous

Open leopoldchen opened this issue 5 years ago • 1 comments

Checklist
  • [x] npm test passes
  • [ ] tests and/or benchmarks are included
  • [ ] documentation is changed or added
  • [ ] commit message follows commit guidelines
Affected core subsystem(s)
Description of change

Current sequelize-ts example can't not pass all test cases, it will raise error while using 'include' operator.

Here is the error log:

SequelizeDatabaseError: Column 'id' in field list is ambiguous

The reason is the sql generated by sequelize was missing the mainTable name, here is the incorrect sql code:

SELECT ``.`id`, ``.`title`, ``.`content`, ``.`user_id`, ``.`created_at`, ``.`updated_at`, ``.`created_at` AS `createdAt`, ``.`updated_at` AS `updatedAt`, ``.`user_id` AS `userId`, `user`.`id` AS `user.id`, `user`.`name` AS `user.name`, `user`.`age` AS `user.age` FROM `posts` AS `` LEFT OUTER JOIN `users` AS `user` ON ``.`user_id` = `user`.`id` WHERE ``.`id` = 1;

Dig into the source code of sequelize we could find out these lines:

// resolve table name options
    if (options.tableAs) {
      mainTable.as = this.quoteIdentifier(options.tableAs);
    } else if (!Array.isArray(mainTable.name) && mainTable.model) {
      mainTable.as = this.quoteIdentifier(mainTable.model.name);
    }

In current example, app.model.Post.name will return empty string, because its model return an anonymous class.

return class extends Post { 
   //...
 }

leopoldchen avatar Mar 22 '20 09:03 leopoldchen

this can help

ZHAOzn avatar Jun 17 '22 03:06 ZHAOzn

this can help

bobby169 avatar Dec 25 '23 10:12 bobby169