CodeIgniter:不使用循环插入多条记录

33

在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);
}
2个回答

81

Codeigniter的活动记录(active record)有一个函数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

链接已更新

Codeigniter 3.x的insert_batch()方法

Codeigniter 2.x的insert_batch()方法


1
这个对于编辑也适用吗?如果记录存在 -> 更新它。如果不存在 -> 插入它。当然,我会将ID添加到内部数组中。 - Pablo Santamaria

2

如果是CodeIgniter 4.x,使用$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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接