我正在尝试使用cakephp 3.x的validCount验证器规则
我有一个活动,参与人数最多(Event-> max_pax)
我想添加一个验证规则,当数量为max_pax + 1时拒绝参与者。
我做错了什么,但我不明白(我的代码如下)
//This is in Participant Model.php
public function buildRules(RulesChecker $rules)
{
$rules->add(
function ($entity, $options) use ($rules) {
$query = $this->Events->find();
$max_pax = $query->select('max_pax')
->where(['id'=>$entity->event_id])
->first();
$r = $rules->validCount('events', $max_pax , '<=', "maximum $max_pax participants");
debug($r);
return $r;
},
'maxPax',
[
'errorField' => 'event_id',
'message' => "Choose another event"
]
);
有人可以帮忙吗?
首先,如果您在哪里嵌套这样的规则,那么您必须对它们进行评估。在您的示例中,$r
将是\Cake\Datasource\RuleInvoker
类型的可调用对象,因此您可以执行以下操作:
$result = $r($entity, $options);
然后进一步评估验证结果(它是一个布尔值),或者从自定义规则中返回它。同样在你的例子中,$max_pax
将是一个实体,你必须实际访问它上面的字段并将其传递给validCount()
方法。
但是,validCount()
用于计算当前存在于给定实体上的关联数据,它不执行任何数据库查找,即它适用于保存包含关联记录的记录,并且想要定义限制的情况。可以/必须保存的关联记录的数量。因此,如果您在哪里创建包括参与者在内的新事件,您可以使用它,以确保您不会尝试插入超过允许的参与者。
通过参与者模型创建记录时,您希望实际查询数据库,以便计算已与所选事件关联的参与者数量。没有内置规则可以做到这一点,所以你必须自己做,例如:
$event = $this->Events
->find()
->select(\Cake\ORM\Query $query) {
return [
'Events.max_pax',
'number_of_participants' => $query->func()->count('Participants.id')
];
})
->leftJoinWith('Participants')
->where(['Events.id' => $entity->event_id])
->first();
return $event->get('number_of_participants') < $event->max_pax;
这将查询允许的最大参与者数量和已存在的参与者数量,然后简单地比较这些值。