duancai9010 2016-02-14 19:35
浏览 181
已采纳

Yii2无效呼叫:设置只读属性

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?

  • 写回答

1条回答 默认 最新

  • dongxuan2015 2016-02-14 20:03
    关注

    Here 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.

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

    So you are given error of Setting read-only property.

    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'],
            ];
        }
        // ... 
    

    In view file

    <?= $form->field($model, 'tg')->textInput(['value'=>$model->stringTags()]) ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥30 用arduino开发esp32控制ps2手柄一直报错
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿