Save related(one to one) Model in YII having reference of parent -
i'm having trouble on inserting new record having parent .
<?php /** * model class table "tbl_a". * @property integer $id .... */ class extends cactiverecord{ } ?> <?php /** * model class table "tbl_b". * @property integer $id .... * followings available model relations: * @property $a */ class b extends cactiverecord{ //codes... /** * @return array relational rules. */ public function relations() { // note: may need adjust relation name , related // class name relations automatically generated below. return array( 'a' => array(self::belongs_to , 'a', 'id'), ); } } ?> this structure of model classes. here 'id' of tbl_b set primary key , foreign key referencing tbl_a. 'id' of tbl_a primary key.
my issue here is, when tried save model object of b ($b->save()), after setting attributes excluding 'id' (but property 'a' of object[$b] set active record of model 'a' having primary key 10), exception thrown on inserting record because of no 'id' set it. when tried same after setting 'id' of model object, inserted correctly. why need set foreign key attribute of child model related property set? there solution this. foreign key reference id taken automaticaly related model obj?
thanks in advance.
is automatically generated if database support it. yii not create id himself. if using mysql rdms, primary key should marked auto_increment. in situation, using foreign key primary key. preferable way overload beforesave method of b model , fetch a::id b::id:
public function beforesave() { if (parent::beforesave()) { $this->id = $this->a->id; return true; } return false; }
Comments
Post a Comment