我正在使用laravel和mongodb开发酒店预订可用性检查。我很困惑写查询来查找可用日期。我尝试了一种方法,但它就像between and
。我不确定查询是否正确。
我在这个问题中包含了laravel raw query和mongo query。两者都是一样的。
为什么查询不正确?
因为,访客在2017-09-02
上查看并在2017-09-05
结帐。目前我正在获取2017-09-02 >= checkin_from && 2017-09-05 <= checkin_from
等数据。如果2017-09-02
是checkin_from
日期,那么这是正确的。但如果checkin_from
为2017-08-25
而reserve_to
为2017-09-06
。此处的日期2017-09-02 to 2017-09-05
包括在内。在这种情况下,我们将如何检查?
这可以通过查询吗?
或
数组1:获取所有预订并存储在数组中。
数组2:然后使用DatePeriod和DateInterval准备日期(从前端签入和签出日期)并存储在数组中。然后检查匹配的数组(1和2)。
我遵循哪种方法?
查询目前我正在使用
$bookings = Booking::raw(function ($collection) use ($dateBegin, $dateEnd) {
return $collection->aggregate([
[
'$match' => [
'cabinname' => 'test',
'checkin_from' => ['$gte' => $dateBegin, '$lte' => $dateEnd],
'is_delete' => 0,
],
],
[
'$project' => [
'beds' => 1,
'dormitory' => 1,
'sleeps' => 1,
'status' => 1,
'has status' => [
'$in' => ['status', ['1', '4', '5', '7']]
]
],
]
]);
});
Mongo查询
db.booking.aggregate([
{
$match: {
"cabinname" : 'Test',
"checkin_from" : {$gte :[ new Date ('2017-09-01') ], $lte : [ new Date ('2017-09-03') ] },
"is_delete" : 0,
}
},
{
$project: {
"beds" : 1,
"cabinname":1,
"checkin_from":1,
"reserve_to":1,
"has status" : {
$in: [ "status", ['1', '4', '5', '7'] ]
}
}
}
])
数据库中的数据
{ "_id" : ObjectId("5888fbd5d2ae672245fb5f79"), "cabinname" : "Test", "checkin_from" : ISODate("2017-08-29T22:00:00Z"), "reserve_to" : ISODate("2017-09-03T22:00:00Z"), "beds" : "8" }
{ "_id" : ObjectId("58a4812bd2ae67066eeaea41"), "cabinname" : "Test", "checkin_from" : ISODate("2017-09-01T22:00:00Z"), "reserve_to" : ISODate("2017-09-05T22:00:00Z"), "beds" : "18" }
{ "_id" : ObjectId("58bac8a5d2ae67951845edaf"), "cabinname" : "Test", "checkin_from" : ISODate("2017-09-01T22:00:00Z"), "reserve_to" : ISODate("2017-09-02T22:00:00Z"), "beds" : "0" }
{ "_id" : ObjectId("58d03541d2ae671c668b4568"), "cabinname" : "Test", "checkin_from" : ISODate("2017-09-02T22:00:00Z"), "reserve_to" : ISODate("2017-09-04T22:00:00Z"), "beds" : "14" }
答案 0 :(得分:0)
由于条件错误,我的查询无效。我已经更新了条件,现在我得到了确切的结果。
{checkin_from:{$lte: new Date ('2017-09-02')}, reserve_to:{$gt: new Date ('2017-09-02')}}
$bookings = Booking::raw(function ($collection) use ($dateBegin, $dateEnd) {
return $collection->aggregate([
[
'$match' => [
'cabinname' => 'test',
'checkin_from' => ['$lte' => $dateBegin],
'reserve_to' => ['$gt' => $dateBegin],
'is_delete' => 0,
],
],
[
'$project' => [
'beds' => 1,
'dormitory' => 1,
'sleeps' => 1,
'status' => 1,
'has status' => [
'$in' => ['status', ['1', '4', '5', '7']]
]
],
]
]);
});