如何使用`validCount`规则限制当前模型的记录数?

How to use the `validCount` rule to restrict the number of records of the current model?

我正在尝试使用 cakephp 的 validCount 验证器规则 3.x

我有一个活动,有最大参与人数(活动->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);

然后进一步评估验证结果(它是一个布尔值),或者 return 它来自您的自定义规则。同样在您的示例中 $max_pax 将是一个实体,您必须实际访问其上的字段并将其传递给 validCount() 方法。

但是,validCount() 用于计算给定实体上当前存在的关联数据,它不执行任何数据库查找,即它用于保存记录的情况 包括条关联记录,想定义限制can/must保存的关联记录数。因此,例如,如果您要创建一个包括参与者在内的新活动,您可以使用它,以确保您不会尝试插入超过允许的参与者。

当通过您的参与者模型创建记录时,您想要实际查询数据库以计算有多少参与者已经与所选事件相关联。没有这样做的内置规则,所以你必须自己做,例如:

$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;

那将查询允许的最大参与者数和已经存在的参与者数,然后简单地比较这些值。