CodeIgniter:插入多个记录而不循环
可以在CodeIgniter活动记录中使用多个插入记录,而无需for、foreach等 我当前的代码:CodeIgniter:插入多个记录而不循环,codeigniter,activerecord,codeigniter-2,Codeigniter,Activerecord,Codeigniter 2,可以在CodeIgniter活动记录中使用多个插入记录,而无需for、foreach等 我当前的代码: foreach($tags as $tag) { $tag = trim($tag); $data = array( 'topic_id' => $topic_id, 'user_id' => $user_id, 'text' => $tag ); $this->db-
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 active record具有插入批处理功能,我想这就是您需要的
$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 4x,请使用
$builder->insertBatch()
这个版本也适用吗?如果记录存在->更新它。如果它不存在->插入它。当然,我会将id添加到内部数组中。
$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')