Yii2无效调用:正在设置只读属性

jdzmm42g  于 2022-11-09  发布在  其他
关注(0)|答案(3)|浏览(236)

我有一个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是只读的?设置模型关系的正确方法是什么?

9w11ddsr

9w11ddsr1#

这里tags

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

是相关名称,并传回对象,而不仅仅是属性或数据库数据行。
您不能像emailfirst_name等其他属性那样将其与textInput()一起使用。
因此,给出的错误为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()]) ?>
ycl3bljg

ycl3bljg2#

正在设置只读属性:app\models\Post::tags,因为您需要在模型属性中添加$tags:

public $tags;
mrwjdhj3

mrwjdhj33#

在大多数情况下,不需要设置关系。但如果需要:

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关系

相关问题