2014-03-25 61 views
0

表結構,CakePHP的:多列的唯一日期+ ID驗證

id, chart_id, date, rate 
Datapoint belongsTo Chart 

我努力讓自己在chart_id唯一索引驗證規則,日期。我試圖用插件MultiColumnUniqueness進行驗證,但它總是返回true。

編輯:這不是問題。這對於檢查多列唯一性是有效的。見下文。 模型驗證與MultiColumnUniqueness:

public $actsAs = array('MultiColumnUniqueness.MultiColumnUniqueness' => array(
     'fields' => array('chart_id', 'date'), 
     'errMsg' => "This date for this chart has already been used." 
)); 

是否有辦法來驗證多列唯一索引與CakePHP的日期?

編輯:我的數據陣列的結構如下:

array(
'Datapoint' => array(
    (int) 0 => array(
     'id' => '1055', 
     'date' => array(
      'month' => '12', 
      'year' => '2012', 
      'day' => '01' 
     ), 
     'active' => '1', 
     'num' => '15', 
     'days' => '897', 
     'chart_id' => '4' 
    ), 
    (int) 1 => array(
     'id' => '1054', 
     'date' => array(
      'month' => '12', 
      'year' => '2012', 
      'day' => '01' 
     ), 
     'active' => '1', 
     'num' => '4', 
     'days' => '768', 
     'chart_id' => '4' 
    ) 
); 

解決:WalkingRed的解決方案工作,以及我所用的插件,但,這是沒有問題的。我在用$ this-> Chart-> validates()保存saveAssociated之前試圖驗證。原來你需要通過不同的方法驗證多行,如果你只是驗證:

if ($this->Chart->saveAssociated($this->request->data, array('validate' => 'only'))) { 
     // validates 
    } else{ 
     $errors = $this->Chart->invalidFields(); //validation error 
    } 

回答

0

你在模型中添加了類似的東西嗎?

public $validate = array(
    'chart_id' => array(
     'unique_first_last' => array(
      'rule' => array('checkMultiColumnUnique', array('chart_id', 'date'), false) 
      'message' => 'Chart and date must be unique.' 
     ) 
    ), 
;) 


public function checkMultiColumnUnique($ignoredData, $fields, $or = true) { 
     return $this->isUnique($fields, $or); 
}