2017-01-01 48 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

我不明白你現在要求什麼。 –