简体   繁体   中英

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(); 
        }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM