In a simple project with Yii I have a model:
Checkins.php
* The followings are the available columns in table 'checkins':
* @property integer $id
* @property integer $user_id
* @property integer $item_id
* @property double $lat
* @property double $long
The two values $user_id and $item_id belong to other two tables:
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'user' => array(self::BELONGS_TO, 'Users', 'user_id'),
'item' => array(self::BELONGS_TO, 'Items', 'item_id'),
);
}
I defined some validator:
public function rules()
{
// NOTE: you should only define rules for those attributes that
// will receive user inputs.
return array(
array('user_id, item_id, lat, long', 'required'),
array('item_id', 'exist', 'on'=>'create', 'attributeName'=>'id', 'className'=>'Items'),
array('user_id, item_id', 'numerical', 'integerOnly'=>true),
array('lat, long', 'numerical'),
// The following rule is used by search().
// Please remove those attributes that should not be searched.
array('id, user_id, item_id, lat, long', 'safe', 'on'=>'search'),
);
}
When in the actionCreate the method save() execute all the validators are working but not the one designed to check the presence of the external key in the model Items
array('item_id', 'exist', 'on'=>'create', 'attributeName'=>'id', 'className'=>'Items'),
And in case I try to save a Checkins that has a value in item_id without having the same id in the Items I don's any validation error.
Is this the right approach?
Thanks
I think it is most likely because you don't set the model's scenario to 'create'
before saving (I'm just guessing that, because you don't attach the $checkin->save()
code in the controller's actionCreate
.). The other validation worked most likely because they aren't set to a specific scenario (i.e. they will work in all validation.).
For example if there is no Item with id 5, the code below
$checkin = new Checkin();
$checkin->text = 'test';
$checkin->item_id = 5;
if (!$checkin->validate()){
print_r($checkin->errors);
}
will work normally since the Checkin
's scenario is not set to 'create'
(the default is 'insert'
). But I tried the code below
$checkin = new Checkin();
$checkin->scenario = 'create';
//or you can set it in the instantiation
//$checkin = new Checkin('create');
$checkin->text = 'test';
$checkin->item_id = 5;
if (!$checkin->validate()){
print_r($checkin->errors);
}
This will result a validation error.
Can you paste your model saving code?