gpt4 book ai didi

node.js - 如何在 sequelize 中关联表格

转载 作者:行者123 更新时间:2023-12-03 22:27:02 27 4
gpt4 key购买 nike

我有这个函数需要查询 3 个不同的表。
表格如下:

DelegateUserLink

id
DelegateId (int)
UserId (int)

Delegate

id (int)
createdBy (int)

User

id (int)
name (varchar)

我开始以这种方式创建关联:
models.DelegateUserLink.belongsTo(models.Delegate);
models.Delegate.belongsTo(models.User, {through: models.Delegate.createdBy});

然后我运行看起来像这样的查询:
return models.DelegateUserLink.findAll({
where: { UserId: id }
,include: {model: models.Delegate,attributes: ['createdBy'],include: {model: models.User,attributes: []}}
}).then(function(rs) {
rs.forEach(function(result) {
console.log("result:",result);
});
return rs;
});

执行此查询会出现此错误:
SequelizeDatabaseError: column Delegate.UserId does not exist        

查看生成的查询,我看到了:
SELECT "DelegateUserLink"."createdAt", "DelegateUserLink"."updatedAt", "DelegateUserLink"."DelegateId", "DelegateUserLink"."UserId", "Delegate"."id" AS "Delegate.id", "Delegate"."createdBy" AS "Delegate.createdBy" FROM "DelegateUserLinks" AS "DelegateUserLink" LEFT OUTER JOIN "Delegates" AS "Delegate" ON "DelegateUserLink"."DelegateId" = "Delegate"."id" LEFT OUTER JOIN "Users" AS "Delegate->User" ON "Delegate"."UserId" = "Delegate->User"."id" WHERE "DelegateUserLink"."UserId" = 677; 

我的想法是通过使用这一行告诉 sequelize 在连接表 DelegateUser 时使用哪个字段
models.Delegate.belongsTo(models.User, {through: models.Delegate.createdBy});

我在哪里指定了“通过”连接应该完成的字段。但显然我错了。因为它尝试使用不存在的 Delegate.UserId (并给出错误)。加入时如何指定使用哪个字段?

最佳答案

好的,这是关于使用关键字“foreignKey”,如下所示:

models.Delegate.belongsTo(models.User, {foreignKey: 'createdBy'});

关于node.js - 如何在 sequelize 中关联表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54181790/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com