Express 包含where条件,但在包含之前保留所有结果
我在查询包含的内部时遇到问题 我所做的是Express 包含where条件,但在包含之前保留所有结果,express,sequelize.js,Express,Sequelize.js,我在查询包含的内部时遇到问题 我所做的是 const courses = await Course.findAll({ subQuery: false, order: [ [ 'courseID', 'ASC' ] ], include: [ { model: CourseAvailable, as: 'courseAvailable', where: {
const courses = await Course.findAll({
subQuery: false,
order: [ [ 'courseID', 'ASC' ] ],
include: [
{
model: CourseAvailable,
as: 'courseAvailable',
where: {
id: 350 // dummy condition only for asking here ( I had my purpose )
}
}
]
});
以及输出
{
"success": true,
"data": [
{
"id": 20,
"courseID": "MTH102",
"courseName": "MATHEMATICS II",
"required": "{MTH101}",
"createdAt": "2020-05-19T17:30:44.085Z",
"updatedAt": "2020-05-19T17:30:44.085Z",
"courseAvailable": [
{
"id": 350,
"courseID": "MTH102",
"semester": 2,
"credit": 3,
"totalSeat": 150,
"section": "7",
"allowedGroup": "EET 1 A(0)",
"day": "จ.",
"start": "10.30",
"end": "12.30",
"classroom": "CB1103",
"createdAt": "2020-05-20T15:22:50.176Z",
"updatedAt": "2020-05-20T15:22:50.176Z"
}
]
}
]
}
从输出中,我知道在include中查询只会返回在include中查询到的课程(正如您所看到的,返回的数据中只有1门课程)
但我仍然希望在include中进行查询,使include仅在满足我的条件时才显示(如过滤include)
但问题是,我还想保留我的其他课程,这些课程不符合任何条件
预期产量
{
"success": true,
"data": [
{
"id": 19,
"courseID": "MTH101",
"courseName": "MATHEMATICS I",
"required": null,
"createdAt": "2020-05-19T17:30:44.085Z",
"updatedAt": "2020-05-19T17:30:44.085Z",
"courseAvailable": [] // showing empty array if none has met my query => still keep the data above
},
{
"id": 20,
"courseID": "MTH102",
"courseName": "MATHEMATICS II",
"required": "{MTH101}",
"createdAt": "2020-05-19T17:30:44.085Z",
"updatedAt": "2020-05-19T17:30:44.085Z",
"courseAvailable": [
{
"id": 350,
"courseID": "MTH102",
"semester": 2,
"credit": 3,
"totalSeat": 150,
"section": "7",
"allowedGroup": "EET 1 A(0)",
"day": "จ.",
"start": "10.30",
"end": "12.30",
"classroom": "CB1103",
"createdAt": "2020-05-20T15:22:50.176Z",
"updatedAt": "2020-05-20T15:22:50.176Z"
}
]
}
]
}
如前所述,在include中使用where时,Sequilize将执行内部联接。您需要在include中设置属性
required:false
,以执行左连接。将您的查询更改为
const courses = await Course.findAll({
subQuery: false,
order: [ [ 'courseID', 'ASC' ] ],
include: [
{
model: CourseAvailable,
as: 'courseAvailable',
where: {
id: 350 // dummy condition only for asking here ( I had my purpose )
},
required: false
}
]
});
如前所述,在include中使用where时,Sequilize将执行内部联接。您需要在include中设置属性
required:false
,以执行左连接。将您的查询更改为
const courses = await Course.findAll({
subQuery: false,
order: [ [ 'courseID', 'ASC' ] ],
include: [
{
model: CourseAvailable,
as: 'courseAvailable',
where: {
id: 350 // dummy condition only for asking here ( I had my purpose )
},
required: false
}
]
});
这回答了我的问题,非常感谢。我以前以为我是这样做的,但我可能把它放错了地方。这回答了我的问题,非常感谢。我以前以为我是这样做的,但我可能把它放错地方了