Check duplication in more than one conditions in CakePHP Model

Recently, we have requirement in our shopping cart project to check whether the username already exist in the same shop. We would like to have this implemented in the Model class. After digging documentation on a Model class in Cakephp site, here is our code on how to implement it.

Add the custom validation in your model:

public $validate = array(
 'duplicate' => array(
 'rule' => array('checkDuplicate'),
 'message' => 'This username already taken.',
 'on' => 'create'
 ),
 ),
);

Here the function to do the checking:

/**
 * Check duplicate username by shop_id
 *
 * @param array $check
 * @return boolean
 */

 public function checkDuplicate($check) {
 $valid = true;

 $count = $this->find('count', array('conditions' => array(
 'Manager.username' => $check['username'],
 'Manager.shop_id' => $this->data[$this->name]['shop_id'],
 )));

 if ($count > 0) {
 $valid = false;
 }

 return $valid;
 }

In this case, we checked the duplication with two conditions: equal with username and shop_id. You can change the field accordingly as per your needs. Hope this help.

Share

Leave a Reply

Your email address will not be published. Required fields are marked *