gpt4 book ai didi

javascript - 在where子句中进行sequelize join来关联两个表

转载 作者:行者123 更新时间:2023-12-02 23:56:09 24 4
gpt4 key购买 nike

我有两个表 t1 和 t2 一对多相关,t1 有 id 主键,t2 有 id 作为外键

如何在 sequalize 中查询以使用联接查找 t2 中 t1.id ='value' 的记录

它应该给出 res,如以下 sql 查询给出

SELECT[t2].[id], [t2].[c1], [t2].[c2], [t2].[c3], [t2].[c4], [t1].[id] AS[t1.id], [t1].[cID] AS[t1.cID] FROM[t2] AS[t2] INNER JOIN[t1] AS[t1] ON[t2].[id] = [t1].[id] AND[t1].[cID] = 'value' WHERE[t2].[sF] = 'value';

最佳答案

首先我们必须关联两个表 t1 和 t2,作为给定的相关信息,该协会应该作为

t1.hasMany(t2, { foreignKey: 'id' });

t2.belongsTo(t1, { foreignKey: 'id' })

然后

t2.findAll(
{
attributes: ['id','c1','c2','c3','c4'
],
required: true,
where: {
sF: 'value',
},
include: [
{
model: t1,
attributes: ['cID'],
required: true,
where: {
cID:'value',
}
}
]
} ).then((result)=>{console.log(result)})

假设 t1 和 t2 是在 sequalize 中声明的模型

关于javascript - 在where子句中进行sequelize join来关联两个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55377385/

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