Yii2以Active Record的多对多关系更新联结表

tya*_*yan 5 php mysql yii2

我有3个表.例如,文章表,标签表,数据库中的article_tag表.文章和标签有NM关系.

当我需要添加新文章时,使用Yii2的活动记录的link()方法将关系保存到联结表,它可以正常工作.

但是当我需要更新联结表时.如果我再次调用文章上的link()方法.不起作用.下面是我的代码和错误信息.

$tag_ids = Yii::$app->request->post('Article')['tags'];
foreach ($tag_ids as $value) {
   $tag = Tag::findOne($value);
   $model->link('tags', $tag);
}

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '13-1' for key 'PRIMARY'
The SQL being executed was: INSERT INTO `article_tag` (`article_id`, `tag_id`) VALUES (13, 1)
Run Code Online (Sandbox Code Playgroud)

我是否需要删除联结表中的所有数据然后使用link()来更新它?或者Yii2中有一些我缺少的功能?

------------------------更新------------------------- ----------------

看来我需要自己用纯sql来做.我想到的最简单的方法是首先删除联结表中的数据,然后使用link()再次填充数据透视表.这很简单,但会搞砸索引.桌子也快速增长.第二种方法是读取每条记录然后决定保留或删除它.然后添加必要的数据.这样会使它更复杂.需要更多的代码.

----------------再次更新我写了一个函数------------------------

public function syncTags($new_tag_ids){

    $old_tag_ids = ArrayHelper::getColumn($this->tags, 'id');

    $tag_to_delete = array_diff($old_tag_ids, $new_tag_ids);
    $tag_to_add = array_diff($new_tag_ids, $old_tag_ids);

    if($tag_to_delete){
      //delete tags
      Yii::$app->db->createCommand()
          ->delete('article_tag', ['article_id' => $this->id, 'tag_id' => $tag_to_delete])
          ->execute();
    }

    if($tag_to_add){
      //link new tag assisoated with the article
      foreach ($tag_to_add as $value) {
        $tag = Tag::findOne($value);
        $this->link('tags', $tag);
      }
    }
}
Run Code Online (Sandbox Code Playgroud)

它现在已经开始了,但并非全球适用.我认为它可能会帮助人们如此发布.Yii需要扩展这类工作..

Pra*_*rti 2

大多数时候我只使用这种方法。第二个解决方案也有效,但我更喜欢第一个。我是那种喜欢在没有别人分机帮助的情况下解决问题的人。

/**
 * Update categories with the new ones
 * @param  array  $categories [description]
 * @return null
 */
public function updateCategories($categories = [])
{
    $this->unlinkAll('categories', true);

    if ( ! is_array($categories))
        return ;

    foreach ($categories as $category_id)
    {
        $category = Category::findOne($category_id);
        $this->link('categories', $category);
    }

    // alternative solution

    /*
    $old_categories = $this->getCategories()->asArray()->column(); // get all categories IDs
    if ( ! is_array($categories))
        $categories = [];

    $inserted_categories = array_diff($categories, $old_categories);
    $deleted_categories = array_diff($old_categories, $categories);

    foreach ($inserted_categories as $category_id)
    {
        $category = Category::findOne($category_id);
        $this->link('categories', $category);
    }

    foreach ($deleted_categories as $category_id)
    {
        $category = Category::findOne($category_id);
        $this->unlink('categories', $category, true);
    }
    */
}
Run Code Online (Sandbox Code Playgroud)