我的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 \ InvalidCallException
设置只读属性:app \ models \ Post :: tags
控制器正在使用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
只读?什么是建立模型关系的正确方法?
答案 0 :(得分:4)
此处tags
public function getTags(){
return $this->hasMany(Tags::className(), ['id' => 'tag_id'])
->viaTable('post_tags', ['post_id' => 'id']);
}
是一个关系名称并返回该对象,而不仅仅是属性或数据库列。
您不能将其与textInput()
一样用于其他属性,例如email
,first_name
。
因此,您会收到Setting read-only property
的错误。
为了消除此错误,您需要创建新的属性或属性以进行建模,如下所示
class Post extends \yii\db\ActiveRecordsd
{
public $tg;
public function rules()
{
return [
// ...
['tg', 'string', 'required'],
];
}
// ...
在视图文件中
<?= $form->field($model, 'tg')->textInput(['value'=>$model->stringTags()]) ?>
答案 1 :(得分:0)
在大多数情况下,不需要设置关系。但是,如果您需要它:
php composer.phar require la-haute-societe/yii2-save-relations-behavior "*"
型号
class Post extends yii\db\ActiveRecord
{
public function behaviors()
{
return [
'saveRelations' => [
'class' => SaveRelationsBehavior::class,
'relations' => [
'author',
],
],
];
}
}
现在此代码不会导致错误Setting read-only property
=)
$post->author = Author::findOne(2);
此外,模块yii2-save-relations-behavior帮助保存更容易的hasMany
关系
答案 2 :(得分:0)
设置只读属性:app \ models \ Post :: tags,因为您需要在模型属性中添加$ tags:
public $tags;