根据另一个 sequelize 查询的结果对查询进行 Sequelize
Sequelize query based on results of another sequelize query
我有一个 postgres 数据库,我正在使用 Sequelize。从 tables vehicles 和 bookings 我试图在给定 startDate 和 endDate 的情况下获取所有可用车辆。
如果我使用指定日期搜索预订:
Bookings.findAll({
where: {
[Op.or]: [
{ dateOut : { [Op.gt]: req.body.startDate} },
{ dateIn : { [Op.lt]: req.body.startDate} }
],
[Op.or]: [
{ dateOut : { [Op.gt]: req.body.endDate} },
{ dateIn : { [Op.lt]: req.body.endDate} }
]
}
})
我得到了在这些日期预订的所有车辆。例如,使用 startDate 2020-12-12 和 endDate 2020-12-13 进行搜索会给我这些预订:
[
{
"id": 13,
"startDate": "2020-12-05T00:00:00.000Z",
"endDate": "2020-12-13T00:00:00.000Z",
"vehicleId": 1
},
{
"id": 12,
"startDate": "2020-12-12T00:00:00.000Z",
"endDate": "2020-12-13T00:00:00.000Z",
"vehicleId": 2
}
]
是否可以使用 Sequelize 来 return 车辆 table 中未在此初始搜索中找到的车辆?
更新
根据阿纳托利的回答,我得到了这个。它响应第一个查询的结果:
.then(bookingData => {
const bookedVehicleIds = bookingData.map(x => x.vehicleId)
Vehicles.findAll({
where: {
id: {
[Op.notIn]: bookedVehicleIds
}
}
})
.then(results => {
res.send(results);
})
})
我认为没有简单的方法可以执行一个查询而不是两个查询(仅通过 sequelize.where
和 sequelize.literal
使用 NOT EXISTS
子查询)。
因此,如果您已经有 Booking
个模型实例,您可以只使用 Op.notIn
来获取所有 Vehicles
在给定时间段内未被预订的实例:
const bookings = await Bookings.findAll({
// ... where condition omitted
})
const bookedVehicleIds = bookings.map(x => x.vehicleId)
const notBookedVehicles = await Vehicles.findAll({
where: {
id: {
[Op.notIn]: bookedVehicleIds
}
}
})
我有一个 postgres 数据库,我正在使用 Sequelize。从 tables vehicles 和 bookings 我试图在给定 startDate 和 endDate 的情况下获取所有可用车辆。
如果我使用指定日期搜索预订:
Bookings.findAll({
where: {
[Op.or]: [
{ dateOut : { [Op.gt]: req.body.startDate} },
{ dateIn : { [Op.lt]: req.body.startDate} }
],
[Op.or]: [
{ dateOut : { [Op.gt]: req.body.endDate} },
{ dateIn : { [Op.lt]: req.body.endDate} }
]
}
})
我得到了在这些日期预订的所有车辆。例如,使用 startDate 2020-12-12 和 endDate 2020-12-13 进行搜索会给我这些预订:
[
{
"id": 13,
"startDate": "2020-12-05T00:00:00.000Z",
"endDate": "2020-12-13T00:00:00.000Z",
"vehicleId": 1
},
{
"id": 12,
"startDate": "2020-12-12T00:00:00.000Z",
"endDate": "2020-12-13T00:00:00.000Z",
"vehicleId": 2
}
]
是否可以使用 Sequelize 来 return 车辆 table 中未在此初始搜索中找到的车辆?
更新
根据阿纳托利的回答,我得到了这个。它响应第一个查询的结果:
.then(bookingData => {
const bookedVehicleIds = bookingData.map(x => x.vehicleId)
Vehicles.findAll({
where: {
id: {
[Op.notIn]: bookedVehicleIds
}
}
})
.then(results => {
res.send(results);
})
})
我认为没有简单的方法可以执行一个查询而不是两个查询(仅通过 sequelize.where
和 sequelize.literal
使用 NOT EXISTS
子查询)。
因此,如果您已经有 Booking
个模型实例,您可以只使用 Op.notIn
来获取所有 Vehicles
在给定时间段内未被预订的实例:
const bookings = await Bookings.findAll({
// ... where condition omitted
})
const bookedVehicleIds = bookings.map(x => x.vehicleId)
const notBookedVehicles = await Vehicles.findAll({
where: {
id: {
[Op.notIn]: bookedVehicleIds
}
}
})