31

可以在 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);
}
4

2 回答 2

80

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

更新的链接

Codeigniter 3.x 的 insert_batch()

Codeigniter 2.x 的 insert_batch()

于 2013-02-18T23:08:11.327 回答
1

对于 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')

资源

于 2021-01-14T09:59:20.263 回答