2017-01-01 49 views
1
use App\Model\Rule\CustomIsUnique; 

$rules->add(new CustomIsUnique(['item_id', 'manufacture_unit_id']), [ 
    'errorField' => 'item_id', 
    'message' => 'Item Unit must be unique.' 
]); 

CustomIsUnique编写自定义规则,我复制粘贴isUnique设置为CakePHP的模型

Cake\ORM\Rule\IsUnique; 

但如何的码延长或添加__invoke方法里面更多的操作?

更新 ::

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

这是我如何针对不同的模型来实现,并通过与选项阵列沿额外的参数。我认为这不是做这件事的好方法。

回答

2

如果你想扩展核心应用程序规则,你可以这样做:

<?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 
    } 
} 

,可以让你添加任何额外的逻辑为您的应用。

+0

我不明白你现在要求什么。 –