I have 3 tables. For example, an article table, a tag table, an article_tag table in a database. article and tag are related to NM.
when I need to add a new article using the Yii2 () active write method to maintain relation to the join table, it works fine.
but when I need to update the connection table. if I call the link () method in the article again. it will not work. below is my code and error information.
$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)
Do I need to delete all the data in the connection table and then use the link () to update it? Or is there some kind of feature that I miss in Yii2?
------------------------ update ---------------------- --- ----------------
It seems I need to do this with pure sql. The easiest way to cross my mind is to first delete the data in the connection table and then use the link () to populate the pivot table again. It's simple, but ruining the index. Also the table is growing rapidly. The second way to do this is to read each entry, then decide to save it or delete it. Then add the necessary data. This method makes it more difficult. Simpler code is needed.
---------------- Update again I wrote a function ------------------------
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); } } }
Now this is happening, but not globally. I think it can help people so post here. Yii needs an extension for this kind of work.