【发布时间】:2021-11-08 02:13:18
【问题描述】:
这是我的本机查询,它包括 2 个内部连接。我可以一个接一个地写这个。但是我想从nodejs Sequelize写这个查询。
SELECT *
FROM video_refs r
JOIN accepts a ON a.ComplaintId = r.complaint_id
JOIN vehicles v ON v.acceptId = a.id
WHERE v.vehicleNumber = 'BG345'
我试过了,但这个 Video_Ref 部分不起作用
const foundVehicleList =await Vehicle.findAll({
where: {
vehicleNumber:'BG1234',
},
include: [
{ model: Accept, as: 'Accept', attributes: []},
{ model: Video_Ref, as: 'Video_Ref', attributes: []},
],
attributes: [
[Sequelize.literal('Accept.ComplaintId'),'ComplaintId']
]
});
这些是关系
db.Complaint.hasOne(db.Video_Ref,{foreignKey: 'complaint_id', sourceKey: 'id'});
db.Video_Ref.belongsTo(db.Complaint,{foreignKey: 'complaint_id', targetKey: 'id'});
db.Complaint.hasOne(db.Accept,{foreignKey: 'ComplaintId ', sourceKey: 'id'});
db.Accept.belongsTo(db.Complaint,{foreignKey: 'ComplaintId ', targetKey: 'id'});
db.Accept.hasMany(db.Vehicle, {foreignKey: 'acceptId', sourceKey: 'id'});
db.Vehicle.belongsTo(db.Accept, {foreignKey: 'acceptId', sourceKey: 'id'});
db.Complaint.hasOne(db.Accept,{foreignKey: 'ComplaintId', sourceKey: 'id'});
db.Accept.belongsTo(db.Complaint,{foreignKey: 'ComplaintId ', targetKey: 'id'});
【问题讨论】:
-
这绝对可以使用
sequelize。但是,如果您包含迄今为止尝试过的任何.findAll查询,以及您想要的输出与您收到的输出,它可能会有所帮助。此外,如果您要为video_refs、accepts和vehicles包含最少的sequelize模型定义,那么有人会更容易提供帮助。这将消除问题中的任何歧义。 -
另外,如果你正在寻找可以尝试的东西,
include语句上的 sequelize 文档(序列化为joins)可以在关于急切加载的章节here 中找到。
标签: sql node.js join sequelize.js inner-join