【问题标题】:CodeIgniter: INSERT multiple records without cycleCodeIgniter:无循环地插入多条记录
【发布时间】:2013-02-03 12:01:54
【问题描述】:

可以在 CodeIgniter Active Record 中使用多个 INSERT 记录而不需要 for、foreach 等?

我当前的代码:

foreach($tags as $tag) {
    $tag = trim($tag);
    $data = array(
        'topic_id'  =>  $topic_id,
        'user_id'   =>  $user_id,
        'text'      =>  $tag
    );
    $this->db->insert('topic_tags', $data);
}

【问题讨论】:

    标签: codeigniter activerecord codeigniter-2


    【解决方案1】:

    Codeigniter 活动记录有一个函数insert_batch 我认为这就是你所需要的

    $data = array(
       array(
          'title' => 'My title' ,
          'name' => 'My Name' ,
          'date' => 'My date'
       ),
       array(
          'title' => 'Another title' ,
          'name' => 'Another Name' ,
          'date' => 'Another date'
       )
    );
    
    $this->db->insert_batch('mytable', $data); 
    
    // Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'), ('Another title', 'Another name', 'Another date')
    

    适用于 Codeigniter 3.x 和 Codeigniter 2.2.6

    更新的链接

    insert_batch() for Codeigniter 3.x

    insert_batch() for Codeigniter 2.x

    【讨论】:

    • 这也适用于版本吗?如果记录存在 -> 更新它。如果它不存在-> 插入它。当然,我会将 id 添加到内部数组中。
    【解决方案2】:

    对于 CodeIgniter 4x 使用 $builder->insertBatch()

    $data = [
        [
                'title' => 'My title',
                'name'  => 'My Name',
                'date'  => 'My date'
        ],
        [
                'title' => 'Another title',
                'name'  => 'Another Name',
                'date'  => 'Another date'
        ]
    ];
    
    $builder->insertBatch($data);
    // Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'),  ('Another title', 'Another name', 'Another date')
    

    Source

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-29
      • 1970-01-01
      • 1970-01-01
      • 2021-01-29
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多