I now there are very nice ways for CakePHP to do automatic validation for you. I am interested in th开发者_如何转开发e isUnique one, but for join columns.
Say I have two columns, user1_id, user2_id
How can I input something into the model for this table such that in validation checking, it requires the user1_id/user2_id pair to be unique.
IE, you can't insert user1_id = 1, user2_id = 5 if a row has that already.
Thanks!
I believe you have to use a custom validation method on your model for that. Something like the following:
class MyModel extends AppModel {
var $name = 'MyModel';
var $validate = array(
'user1_id' => array(
'rule' => 'uniqueUserCombination',
'message' => 'This combination of users is already taken!'
)
);
function uniqueUserCombination($check) {
$count = $this->find('count', array(
'conditions' => array(
'user1_id' => $this->data['MyModel']['user1_id'],
'user2_id' => $this->data['MyModel']['user2_id'],
)
));
return $count==0;
}
}
You said "you can't insert user1_id = 1, user2_id = 5 if a row has that already". The code above works for you example, but will allow user1_id = 5, user2_id = 1. If you need to forbid that too, add more conditions to the find
above. It's also recommended that you create a UNIQUE
index on both columns on your database.
精彩评论