Yii2 无效调用:设置只读属性 [英] Yii2 Invalid Call: Setting read-only property

查看:26
本文介绍了Yii2 无效调用:设置只读属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Post 模型,它与 Tags 有很多关系.

I have a Post model that has a many-many relationship with Tags.

在 Post 模型中定义:

Defined in Post model:

public function getTags(){
    return $this->hasMany(Tags::className(), ['id' => 'tag_id'])
        ->viaTable('post_tags', ['post_id' => 'id']);
}

但是 Post::tags 是只读的.因此,当我尝试在 Controller 中设置它们时,出现错误:

But Post::tags is read-only. So when I try to set them in the Controller, I get an error:

无效调用 – yii\base\InvalidCallException

Invalid Call – yii\base\InvalidCallException

设置只读属性:app\models\Post::tags

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]);
}

视图中的输入字段:

<?= $form->field($model, 'tags')->textInput(['value'=>$model->stringTags()]) ?>

为什么 Post::tags 是只读的?建立模型关系的正确方法是什么?

Why is Post::tags read-only? And whats the proper way to set a model relationship?

推荐答案

这里 tags

public function getTags(){
    return $this->hasMany(Tags::className(), ['id' => 'tag_id'])
        ->viaTable('post_tags', ['post_id' => 'id']);
}

是一个关系名称并返回对象,而不仅仅是一个属性或数据库列.

is a relation name and returns the object and is not just a attribute or database column.

您不能像其他属性一样将它与 textInput() 一起使用,例如 emailfirst_name.

You cannot use it with textInput() like other attribute for eg email, first_name.

所以你会得到设置只读属性的错误.

为了消除此错误,您需要创建新的属性或属性来建模,如下所示

In order to remove this error, you need to create new attrbute or property to model like below

class Post extends \yii\db\ActiveRecordsd
{
    public $tg;
    public function rules()
    {
        return [
            // ...
            ['tg', 'string', 'required'],
        ];
    }
    // ... 

在视图文件中

<?= $form->field($model, 'tg')->textInput(['value'=>$model->stringTags()]) ?>

这篇关于Yii2 无效调用:设置只读属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆