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 怎么让数码管亮的同时让led执行流水灯代码
  • ¥20 SAP HANA SQL Script 。如何判断字段值包含某个字符串
  • ¥85 cmd批处理参数如果含有双引号,该如何传入?
  • ¥15 fx2n系列plc的自控成型机模拟
  • ¥15 时间序列LSTM模型归回预测代码问题
  • ¥50 使用CUDA如何高效的做并行化处理,是否可以多个分段同时进行匹配计算处理?目前数据传输速度有些慢,如何提高速度,使用gdrcopy是否可行?请给出具体意见。
  • ¥15 基于STM32,电机驱动模块为L298N,四路运放电磁传感器,三轮智能小车电磁组电磁循迹(两个电机,一个万向轮),如何通过环岛的原理及完整代码
  • ¥20 机器学习或深度学习问题?困扰了我一个世纪,晚来天欲雪,能饮一杯无?
  • ¥15 c语言数据结构高铁订票系统
  • ¥15 关于wkernell.PDB加载的问题,如何解决?(语言-c#|开发工具-vscode)