4
votes

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?

3
please show your controller codeSohel Ahmed Mesaniya
Added that and the relevant part of the viewDan

3 Answers

4
votes

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()]) ?>
0
votes

In most cases, setting a relation is not required. But if you need it:

php composer.phar require la-haute-societe/yii2-save-relations-behavior "*"

Model

class Post extends yii\db\ActiveRecord
{
    public function behaviors()
    {
        return [
            'saveRelations' => [
                'class' => SaveRelationsBehavior::class,
                'relations' => [
                    'author',
                ],
            ],
        ];
    }
}

Now this code will not cause errors Setting read-only property =)

$post->author = Author::findOne(2);

In addition, module yii2-save-relations-behavior help save easier hasMany relations

0
votes

Setting read-only property: app\models\Post::tags because you need add in your model property $tags:

public $tags;