Form not populating foreign key in join table

So I following database setup, i have created a form when creating a blog post with a dropdown for tags however on submit I want it to populate the join table.

The below only works if I manually set the tag ID.


    if ($model->load(Yii::$app->request->post())) {

        $model->save(false);

        $tags->blog_id = $model->id; 

        //$tags->tag_id = 1; 

        $tags->save(false); 

        return $this->redirect(['view', 'id' => $model->id]);

    } else {

        return $this->render('create', [

            'model' => $model,

            'tags' => $brands,

        ]);

    }

Form Field Setup


<?= Html::activeDropDownList($tags, 'tag_id',

  ArrayHelper::map(tags::find()->all(), 'id', 'title')) ?>

Table/Database Structure below:

Blog -id (PK) -title -content

Blog_category -id (PK) -blog_id (FK) -tag_id (FK)

Tags -id -title

So I following database setup, i have created a form when creating a blog post with a dropdown for tags however on submit I want it to populate the join table.

Mysql error when trying to insert data set by form and not manually

Cannot add or update a child row: a foreign key constraint fails

The below only works if I manually set the tag ID.


    if ($model->load(Yii::$app->request->post())) {

        $model->save(false);

        $tags->blog_id = $model->id; 

        //$tags->tag_id = 1; 

        $tags->save(false); 

        return $this->redirect(['view', 'id' => $model->id]);

    } else {

        return $this->render('create', [

            'model' => $model,

            'tags' => $brands,

        ]);

    }

Form Field Setup


<?= Html::activeDropDownList($tags, 'tag_id',

  ArrayHelper::map(tags::find()->all(), 'id', 'title')) ?>

Table/Database Structure below:

Blog -id (PK) -title -content

Blog_category -id (PK) -blog_id (FK) -tag_id (FK)

Tags -id -title

Check weather your primary key in Tags table is defined as auto increment,

Question: Why you need tag_id in blog_category table?

[color="#006400"]/* topics merged. */[/color]