I have a Post
model that has a many-many relationship with Tags
.
Defined in Post model:
public function getTags(){
return $this->hasMany(Tags::className(), ['id' => 'tag_id'])
->viaTable('post_tags', ['post_id' => 'id']);
}
But Post::tags
is read-only. So when I try to set them in the Controller, I get an error:
Invalid Call – yii\base\InvalidCallException
Setting read-only property: app\models\Post::tags
The controller is using load to set all the properties:
public function actionCreate(){
$P = new Post();
if( Yii::$app->request->post() ){
$P->load(Yii::$app->request->post());
$P->save();
return $this->redirect('/posts');
}
return $this->render('create', ['model'=>$P]);
}
The input field in the view:
<?= $form->field($model, 'tags')->textInput(['value'=>$model->stringTags()]) ?>
Why is Post::tags
read-only? And whats the proper way to set a model relationship?