Yas*_*tha 0 sql join inner-join node.js sequelize.js
这是我的本机查询,它包含 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'
Run Code Online (Sandbox Code Playgroud)
我尝试过,但这个 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']
]
});
Run Code Online (Sandbox Code Playgroud)
这些是关系
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'});
Run Code Online (Sandbox Code Playgroud)
我找到了一个答案,比如
SELECT vf.id,vf.reference FROM video_refs vf INNER JOIN complaints c ON vf.`complaint_id` = c.`id` INNER JOIN Accepts a ON c.`id` = a.`ComplaintId` INNER JOIN vehicles vh ON a.`id` = vh.`acceptId` AND vh.`vehicleNumber` = 'BG1234' AND vh.`createdAt` >= '2021-09-06 09:11:38'
const VideoRefList=await Video_Ref.findAll({
include : [
{
model: Complaint,
required: true,
attributes: [],
include: [
{
model: Accept,
required: true,
attributes: [],
include : [
{
model: Vehicle,
required: true,
attributes: [],
where: {
vehicleNumber:'BG1234',
createdAt: {
[Op.gte]: moment().subtract(7, 'days').toDate()
}
},
}
]
}
]
}
],
attributes: [
'id',
'reference'
]
});
Run Code Online (Sandbox Code Playgroud)