为CakePHP模型编写自定义规则
在CustomIsUnique上,我复制了IsUnique的粘贴代码为CakePHP模型编写自定义规则,cakephp,cakephp-3.0,Cakephp,Cakephp 3.0,在CustomIsUnique上,我复制了IsUnique的粘贴代码 use App\Model\Rule\CustomIsUnique; $rules->add(new CustomIsUnique(['item_id', 'manufacture_unit_id']), [ 'errorField' => 'item_id', 'message' => 'Item Unit must be unique.' ]); 但是如何在\u invoke方法中扩展
use App\Model\Rule\CustomIsUnique;
$rules->add(new CustomIsUnique(['item_id', 'manufacture_unit_id']), [
'errorField' => 'item_id',
'message' => 'Item Unit must be unique.'
]);
但是如何在\u invoke方法中扩展或添加更多操作
更新:
Cake\ORM\Rule\IsUnique;
这就是我如何为不同的模型实现的,并将额外的参数与选项一起传递给数组。我认为这不是一个好方法。如果您想扩展核心应用程序规则,可以执行以下操作:
public function __invoke(EntityInterface $entity, array $options)
{
$result = parent::__invoke($entity, $options);
if ($result) {
return true;
} else {
if ($options['type'] == 'item_units') {
$data = TableRegistry::get('item_units')->find()
->where(['item_id' => $entity['item_id'],
'manufacture_unit_id' => $entity['manufacture_unit_id'],
'status !=' => 99])->hydrate(false)->first();
if (empty($data)) {
return true;
}
} elseif ($options['type'] == 'production_rules') {
$data = TableRegistry::get('production_rules')->find()
->where(['input_item_id' => $entity['input_item_id'],
'output_item_id' => $entity['output_item_id'],
'status !=' => 99])->hydrate(false)->first();
if (empty($data)) {
return true;
}
} elseif ($options['type'] == 'prices') {
$data = TableRegistry::get('prices')->find()
->where(['item_id' => $entity['item_id'],
'manufacture_unit_id' => $entity['manufacture_unit_id'],
'status !=' => 99])->hydrate(false)->first();
if (empty($data)) {
return true;
}
}
}
}
我不明白你现在想要什么。
<?php
use App\Model\Rule;
class CustomIsUnique extends Cake\ORM\Rule\IsUnique
{
public function __invoke(EntityInterface $entity, array $options)
{
$result = parent::__invoke($entity, $options);
if ($result) {
// the record is indeed unique
return true;
}
// do any other checking here
// for instance, checking if the existing record
// has a different deletion status than the one
// you are inserting
}
}