【问题标题】:How to associate tables in sequelize如何在sequelize中关联表
【发布时间】:2019-01-14 12:42:46
【问题描述】:

我有这个函数需要查询 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(并给出错误)。如何指定加入时使用的字段?

【问题讨论】:

    标签: node.js postgresql sequelize.js


    【解决方案1】:

    好的,就是使用关键字“foreignKey”,像这样:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-15
      • 1970-01-01
      • 2019-04-14
      • 2016-09-30
      • 2016-07-23
      • 1970-01-01
      • 2018-07-30
      相关资源
      最近更新 更多