Let’s say I have a model with 2 tables : Owner (int: id) and Car (int: id, int:owner_id).
I’m trying to build a validation rule on Car in order to avoid non existing owner_ids to be bound to the Car.owner_id field. I’d like to have this validation rule in the code instead of just using the DB foreign key check, because it allows me to easily display error messages on the form instead on having to process DB exceptions later.
Thus, in my model, I’d like to have something like :
public function rules() {
return array(
array('owner_id', 'in', 'range' => array(11, 12, 13)),
);
}
where 11, 12, 13 are the existing Owner ids.
I can find those ids through code like :
$ars = Yii::app()->db->createCommand("SELECT id FROM owner")->queryAll();
$ids = array();
foreach($ars as $ar) {
$ids[] = $ar['id'];
}
However, I wondered if there is any built in method in Yii allowing to get this array in a more lazy way like “$ids = Owner::model()->findIdsAsArray()” or something similar.
You dont want to do validate a range. Yii provides
CExistValidatorwith aliasexistexactly for foreign key check. Therangevalidator may fail if the owner ids are not continuous ie if we delete an intermediate user. So You can use a validation rule as followsThe above code validates that there exist an
owner_idin the modelOwnerand raises an error if its not exist in the DB.