examples
examples copied to clipboard
fix-sequelize-ts: SequelizeDatabaseError: Column 'id' in field list is ambiguous
Checklist
- [x]
npm testpasses - [ ] 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 {
//...
}
this can help
this can help