CakePHP 2.1 - Custom Validation Rule - Check for Unique Field Value Combination

让人想犯罪 __ 提交于 2019-12-06 03:28:46
joshua.paling

Cake is definitely behaving the way it's supposed to there. The second paramameter that you pass in that 'rule' array is meant to be passed as a static value.

However, your provider_id should be available in $this->data['MyModel']['provider_id']

So you should be able to forget about that second parameter completely, and do:

public function uniqueClick ($ip) {

   $count = $this->find('count', array(
      'conditions' => array(
          'ip' => $ip, 
          'provider_id' => $this->data[$this->alias]['provider_id'])
   ));
   return $count == 0;

}

Hope that helps!

To complement Joshua's answer, the validation array should be build like this:

// Validation rules
public $validate = array(
   'ip' => array(
      'rule' => array('uniqueClick', 'ip'),
      'message' => 'The click is not unique.'
    )
);  
/** 
 * Checks if there are records on the datasource with the same ip and same provider_id
 * 
 */ 
public function uniqueClick ($ip) {
   $count = $this->find('count', array(
      'conditions' => array(
          'ip' => $ip, 
          'provider_id' => $this->data[$this->alias]['provider_id'])
   ));
   return $count == 0;

}

you can also use my rule with is able to work with as many fields as you need

try http://www.dereuromark.de/2011/10/07/maximum-power-for-your-validation-rules/ and https://github.com/dereuromark/tools/blob/master/Model/MyModel.php#L930

so basically the same than you tried:

'ip' => array(
    'validateUnique' => array(
        'rule' => array('validateUnique', array('provider_id')),
        'message' => 'You already have an entry',
    ),
),

You can directly go with this solution without passing anything in validation rules except the custom unique function.

// Validation rules
public $validate = array(
    'ip' => array(
        'rule' => array('uniqueClick'),
       'message' => 'The click is not unique.'
    )
);  
/** 
 * Checks if there are records on the datasource with the same ip and same provider_id
 * 
 */ 
public function uniqueClick ($ip) {
   $count = $this->find('count', array(
      'conditions' => array(
          'ip' => $ip, 
          'provider_id' => $this->data[$this->alias]['provider_id'])
   ));
   return $count == 0;

}

$this->data[$this->alias]['provider_id'] automatically gets the value of the provider_id.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!