我有一个Post
模型,它与Tags
有多对多关系。
在Post模型中定义:
public function getTags(){
return $this->hasMany(Tags::className(), ['id' => 'tag_id'])
->viaTable('post_tags', ['post_id' => 'id']);
}
但是Post::tags
是只读的,所以当我试图在Controller中设置它们时,我得到一个错误:
无效调用- yii\base\无效调用异常
正在设置只读属性:应用\模型\帖子::标签
控制器正在使用load来设置所有属性:
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]);
}
视图中的输入字段:
<?= $form->field($model, 'tags')->textInput(['value'=>$model->stringTags()]) ?>
为什么Post::tags
是只读的?设置模型关系的正确方法是什么?
3条答案
按热度按时间9w11ddsr1#
这里
tags
是相关名称,并传回对象,而不仅仅是属性或数据库数据行。
您不能像
email
、first_name
等其他属性那样将其与textInput()
一起使用。因此,给出的错误为
Setting read-only property
。要删除此错误,您需要创建新的属性或特性以进行建模,如下所示
在视图文件中
ycl3bljg2#
正在设置只读属性:app\models\Post::tags,因为您需要在模型属性中添加$tags:
mrwjdhj33#
在大多数情况下,不需要设置关系。但如果需要:
型号
现在此代码不会引起错误
Setting read-only property
=)此外,模块yii2-save-relations-behavior帮助保存更容易的
hasMany
关系