2013-02-18 108 views
21

可以在CodeIgniter Active Record中使用多条插入记录,而不需要for,foreach等。CodeIgniter:插入多条记录,无循环

我当前的代码:

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); 
} 

回答

56

笨的活动记录有功能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') 

同时适用于笨3.x和笨2.2.6

UPDATED LINKS

insert_batch() for Codeigniter 3.x

insert_batch() for Codeigniter 2.x

+0

这是否工作版本呢?如果记录存在 - >更新它。如果它不存在 - >插入它。当然,我会将ID添加到内部数组。 – 2017-08-02 12:10:59