我有'accommod_units'
和'accommod_bookings'
表,我想检查一段时间内住宿单位的空房情况。例如,到达日期:2019-08-20和出发日期:2019-08-27。
'accommodation_units'
表如下所示:
'accommod_bookings'
表如下所示:
此代码无效:
$this->loadModel('AccommodUnits');
$this->conditionBookings = [
'NOT' => [
[
'AccommodBookings.date_start >=' => '2019-08-20',
'AccommodBookings.date_end <=' => '2019-08-27'
],
]
];
$accommodUnits = $this->AccommodUnits
->find('all')
->distinct(['AccommodUnits.id'])
->contain([
'AccommodBookings' => function ($q) {
return $q->where($this->conditionBookings);
},
])
->where($conditionUnits)
->matching('AccommodBookings', function ($q) {
return $q->where($this->conditionBookings);
});
他们的关联是:
$accommodUnits->hasMany('AccommodBookings');
如何解决这个问题?
答案 0 :(得分:1)
简单,您必须重叠预订期
[
'AccommodBookings.date_start <=' => '2019-08-27', // Here put end date greater than start date <=
'AccommodBookings.date_end >=' => '2019-08-20' // Here put start date smaller than end date >=
],
现在:
$this->loadModel('AccommodUnits');
$accommodBookings = [
'AccommodBookings.date_start <=' => '2019-08-27', // not match start date lower than end date
'AccommodBookings.date_end >=' => '2019-08-20' // not mach end date greater than start date
];
$accommodUnits = $this->AccommodUnits
->find() // if empty default is 'all'
->where(['AccommodUnits.id' => 124]) // find units 124 where not matching:
->notMatching('AccommodBookings', function ($q) use ($accommodBookings) {
return $q->where($accommodBookings);
});
如果单元124的预订日期重叠,则结果为空。
matching()的反义词不是notMatching()。该功能将改变 查询,以便它过滤与结果无关的结果 指定的关联:
// In a controller or table method.
$query = $articlesTable
->find()
->notMatching('Tags', function ($q) {
return $q->where(['Tags.name' => 'boring']);
});
以上示例将查找所有未使用标记的文章 单词无聊。
Poz