this is the my first post and I'm really confused with the below code. I'm building a gaming website (my first project using yii) and I'm using afterSave() in the model to insert data to another table because the relation is Many to Many. I'm fetching data from database then exploding it to get numbers only (so I can insert it in the other table) instead of ('2','|','3'). The problem is foreach is inserting one row instead (despite the fact it should insert more than one row) of two in my example and the inserted con_id value is always 1, I don't understand the issue here, please help me.
protected function afterSave()
{
$model1 = new GameConsole();
$con[] = explode('|', $this->con_id);
foreach($con as $row) {
$model1->game_id = $this->game_id;
$model1->con_id = $row;
$model1->save(false);
}
parent::afterSave();
}
you are saving one model over and over
you should change your code like this:
protected function afterSave()
{
$con[]= explode('|', $this->con_id);
foreach($con as $row){
$model1=new GameConsole; // this line creates new GameConsole
$model1->game_id= $this->game_id;
$model1->con_id=$row;
$model1->save(false);
}
return parent::afterSave(); // update : return it
}
and btw why are you not validating?