【发布时间】:2021-03-28 06:38:19
【问题描述】:
我有一个应用程序,我需要验证工作时间以确保它们在 CakePHP 3 中不重叠。所有记录都可以在一个表单中更改。数据看起来有点像这样:
| id | day | opening_time | closing_time |
|---|---|---|---|
| 1 | 1 | 08:00:00 | 13:00:00 |
| 2 | 1 | 16:00:00 | 22:00:00 |
现在,当我将第一个 opening_time 更改为 17:00 时,这将是无效的,因为它会与第二行重叠。但是当我以相同的形式将第二个 opening_time 更改为 18:00 时,它应该是有效的。
我尝试使用 buildRules:
public function buildRules(RulesChecker $rules)
{
$rules->add($rules->existsIn(['store_id'], 'Stores'));
$rules->add(
function (BusinessHour $entity, array $options): bool {
$conditions = [
'id !=' => $entity->id,
'store_id' => $entity->store_id,
'day' => $entity->day,
'OR' => [
[
'opening_time <=' => $entity->opening_time,
'closing_time >=' => $entity->opening_time,
],
[
'opening_time <=' => $entity->closing_time,
'closing_time >=' => $entity->closing_time,
],
[
'opening_time >=' => $entity->opening_time,
'opening_time <=' => $entity->closing_time,
],
[
'closing_time >=' => $entity->opening_time,
'closing_time <=' => $entity->closing_time,
]
]
];
return !$options['repository']->exists($conditions);
},
'overlapping',
[
'errorField' => 'opening_time',
'message' => __('Business hours may not overlap.'),
]
);
return $rules;
}
但它会根据数据库中的数据检查第一条记录并标记为无效,即使第二行的更改使其有效。例如,当数据库中的数据如上所述并且我有以下发布数据时,它应该是有效的,但不是。
$data['business_hours'] = [
(int) 0 => [
'day' => '0',
'opening_time' => [
'hour' => '16',
'minute' => '30'
],
'closing_time' => [
'hour' => '17',
'minute' => '00'
]
],
(int) 1 => [
'day' => '0',
'opening_time' => [
'hour' => '18',
'minute' => '00'
],
'closing_time' => [
'hour' => '20',
'minute' => '00'
]
],
];
我应该如何处理这个问题?
【问题讨论】:
-
那么你的代码有什么问题?你的问题并没有真正指向任何具体的东西。或者更具体地说,您的问题是查询没有获得正确的结果,还是之后发生的事情,即“标记无效”?或者两者兼而有之?
-
@ndm 谢谢指出。我试图澄清我的问题。查询得到了正确的结果,但它会根据数据库检查单个条目,并且不会考虑其他更改。
标签: php validation cakephp orm cakephp-3.x