Connor Brough
Connor Brough

Reputation: 579

How do I populate a join table using Yii2?

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

UPDATE:

Not sure if the below is the best way however it works, any improvements welcomed.

        foreach ($_POST['Tags']['tag_id'] as $tag){
            $tags = new Tags();
            $tags->blog_id = $model->id;
            $tags->tag_id = $tag; 
            $tags->save(); 
        }

Upvotes: 0

Views: 121

Answers (1)

ScaisEdge
ScaisEdge

Reputation: 133380

Have you tried using tags in assignment

if ($model->load(Yii::$app->request->post())) {
    $modelTags = load(Yii::$app->request->post('tags')));
    $model->save(false);
    $tags->blog_id = $model->id; 
    $tags->tag_id = $modelTags->tag_id; 
    $tags->save(false); 
    return $this->redirect(['view', 'id' => $model->id]);
} else {
    return $this->render('create', [
        'model' => $model,
        'tags' => $brands,
    ]);
}

PS the use of ->save(false) should be limited to the test phase in case of validation problems. If you don't remove this flag you could be inconsistent set of data in db.

Upvotes: 2

Related Questions