CodeIgniter insert_batch()
好吧,我试图弄清楚如何使用insert_batch
OK i am trying to figure how to use insert_batch
我正在尝试这样的事情
function checkboxes($data,$category)
{
$insert=array(
'story'=>$data
'category'=>$category
);
$this->db->insert_batch('stories_to_categories',$insert);
}
对于$ data,我有数组,该数组可以具有值和键的范围
For $data i have array, which could have range of values and keys
(
[0] => 1
[1] => 6
[2] => 14
[3] => 15
[4] => 18
)
对于类别,我将仅具有一个值,例如2
For category i will have only one value for example 2
我尝试在自己的表格中实现
I try to achive in my tabele
story category
------------------------
1 2
6 2
14 2
15 2
18 2
有人可以帮助我,我很痛苦!
Could someone help me i am in such a pain!
您可以通过以下方法来实现对您的代码进行一些修改。
CI文档显示,批处理插入需要一个嵌入有关联数组的数组:要插入的每个新行都有1个关联数组,将列映射到值。
You can achieve this by making a little modification to your code. CI documentation shows that batch insert expects an array that is embedded with associative arrays: 1 associative array for each new row to be inserted, mapping the column to the value.
实际上,您想为您的 $ insert
建立这样的数组:
Practically, you would want to build an array like this for your $insert
:
$insert=array(
array('story'=>1, 'category'=>2).
array('story'=>6, 'category'=>2).
array('story'=>14, 'category'=>2).
array('story'=>15, 'category'=>2).
array('story'=>18, 'category'=>2).
);
由于类别是常量,因此您可能需要使用以下函数:
Since your category is constant, you might want to use a function:
function _insert_($data, $category='2', $options=array('data'=>'story', 'category'=>'category'))
{
$return = array();
foreach ($data as $value)
{
$return[] = array($options['data']=>$value, $options['category']=>$category);
}
return $return;
}
然后您将获得以下内容:
You can then have something like the following:
$this->db->insert_batch('stories_to_categories',_insert_($data));
希望这会有所帮助。
查找参考(s)如下:
请参阅此处的CodeIgniter参考: CodeIgniter活动记录:#Insert
See CodeIgniter reference here: CodeIgniter Active Record: #Insert
编辑:Codeigniter 3.0查询生成器类:插入数据
edit: Codeigniter 3.0 Query Builder Class: inserting data