我正在尝试将以下原始查询转换为 ORM,但无法实现任何目标。
原始查询
select * from "Invoices" I
LEFT JOIN "Requests" R ON R."id" = I."requestId"
LEFT JOIN "Supps" S ON S."requestId" = R."id"
where S."confirm" = 'OK'
我试过的:
Requests.belongsTo(Invoices, { foreignKey: "id" });
Supps.belongsTo(Requests, { foreignKey: "requestId" });
Supps.hasMany(Requests, { foreignKey: "requestId" });
Invoices.hasMany(Requests, { foreignKey: "requestId" });
Invoices.findOne({
include: [{ model: Requests, required: false }, { model: Supps, required: false }],
where: { Sequelize.col("Supps.confirm"): { "OK" } }
}).then(data => {
console.log(data);
})
但这会生成一个非常长的查询,其中包含多个子查询和错误数据
最佳答案
当然,您还需要在 th 关联中添加 sourceKey
。 ( doc )
Supps.hasMany(Requests, { foreignKey: "requestId" ,sourceKey: '{ID}' });
Invoices.hasMany(Requests, { foreignKey: "requestId",sourceKey: '{ID}' });
您也可以添加
{raw:true}
以获得一级 json 响应。 Invoices.findOne({
include: [{ model: Requests, required: false }, { model: Supps, required: false }],
where: { Sequelize.col("Supps.confirm"): { "OK" } },
raw:true
}).then(data => {
console.log(data);
});
关于orm - 使用 Sequelize 连接 3 个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60073614/