Sequelize Join 非主键 [英] Sequelize Join on Non Primary Key

查看:20
本文介绍了Sequelize Join 非主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要关联两个表.表 A 有一个表 B.我可以在 TableA 模型中做到这一点:

I have two tables I need to associate. TableA has One TableB. I'm able to do this in the TableA Model:

TableA.hasOne( models.TableB, { as: 'TableB', foreignKey: 'someID' } );

查看 SQL,它尝试连接 TableA.ID 和 TableB.someID.我真正想要的是加入 TableA.someNonPrimaryKey 和 TableB.someID.

Looking at the SQL, this tries to join TableA.ID and TableB.someID. What I actually want, is to join TableA.someNonPrimaryKey and TableB.someID.

如何让 sequelize 加入 someNonPrimaryKey?

How can I tell sequelize to join with someNonPrimaryKey?

推荐答案

我知道这是旧的;我是为了其他可能需要答案的人而做出回应的.

I know this is old; I am responding for the sake of others that might need the answer.

您现在可以在非主键列上关联表.在您的情况下,关联将是:

You can now associate tables on non-primary key columns. In your case, the association would be:

TableA.hasOne(TableB, {
  sourceKey: 'someNonPrimaryKeyColumnOnTheSOurceModel',
  foreignKey: 'matchingColumnOnTheTargetModel'
});

请注意,列 someNonPrimaryKeyColumnOnTheSOurceModel 必须在模型定义中将 unique 设置为 true.

Please note, the column someNonPrimaryKeyColumnOnTheSOurceModel must have unique set to true in the model definition.

您可以在此处阅读更多信息:https://sequelize.org/master/manual/assocs.html

You can read more about it here: https://sequelize.org/master/manual/assocs.html

这篇关于Sequelize Join 非主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆