简体   繁体   English

从INSERT IGNORE语句获取多个插入ID

[英]Get multiple insert IDs from INSERT IGNORE statement

I want to realize a tag feature for article posts, so a user can add several tags when posting an article. 我想实现文章发布的标签功能,因此用户在发布文章时可以添加多个标签。

I have a tags table, an articles table and a article_tags table. 我有一个tags表,一个articles表和一个article_tags表。

tags: 标签:

id | tag (Unique)

articles: 文章:

id | title | content

article_tags: article_tags:

id | article_id | tag_id

So (1) when a new article is to insert, I need to insert into the articles table and get the insert id as article_id . 因此(1)当要插入新文章时,我需要将其插入articles表中并获得插入id为article_id

(2) Then, I use a single INSERT IGNORE statement to insert multiple tags into the tags table. (2)然后,我使用一个INSERT IGNORE语句将多个标签插入tags表。 Among these tags, some may exists and will be ignored. 在这些标签中,可能存在一些并且将被忽略。

(3) Now I am about to insert the relations of articles and tags with article_tags . (3)现在,我要插入带有article_tags的文章和标签的关系。 However, how can I get the IDs in step (2) to serve as tag_id in the last table? 但是,如何在步骤(2)中获取ID以用作最后一个表中的tag_id

Or I just cannot (instead, to use a one by one insert solution)? 还是我不能(相反,使用一对一的插入解决方案)?

@AdrienXL's answer is a one-by-one solution. @AdrienXL的答案是一对一的解决方案。

I find that I can first batch insert the tags with INSERT IGNORE . 我发现我可以先使用INSERT IGNORE批量插入标签。

And when I insert the relations for article_tags , I can use a "batch select" query to get the IDs. 当我插入article_tags的关系时,我可以使用“批量选择”查询来获取ID。 So I don't necessarily need to manually fetch and store the tags' IDs in tags table. 因此,我不必手动获取标签的ID并将其存储在tags表中。

The pseudo-SQLs would like: 伪SQL希望:

INSERT IGNORE tags (tag) VALUES [the tag array]

And

INSERT INTO article_tags (tag_id, article_id) 
    SELECT id, [some_article_id] FROM tags WHERE tag IN [the tag array]

Model : 型号:

   public function insert_articles($data)
   {
      $this->db->insert('articles', $data);
      return $this->db->insert_id(); 
   }

   public function insert_tags($data)
   {
     $insert_query = $this->db->insert_string('tags', $data);
     $insert_query = str_replace('INSERT INTO','INSERT IGNORE INTO',$insert_query);
     $this->db->query($insert_query);

     return $this->db->insert_id(); 
   }

   public function insert_article_tags($data)
   {
     return $this->db->insert_batch('articles_tags', $data);
   }

Controller : 控制器:

   public function myfunction()
   {
     $id_article = $this->my_model->insert_articles($data);
     $article_tags = array();
     foreach($mytags as $t)
     {
         $id_tag = $this->my_model->insert_articles($data);
         array_push($article_tags, array("id_article" => $id_article, "id_tag" => $id_tag));
         //Supposed two fields table : id_article | id_tag
     }

     $this->my_model->insert_article_tags($data);
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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