让我们在我的数据库中说我有2张桌子。其中一个名为父, Father_id 为 PK , Father_name 为行。然后,第二个表格为儿童, Child_id 为 PK , Father_id 为 FK 和 Child_name 作为一行。
孩子们会与父亲成为多对一的关系。许多孩子对一个父亲。
所以,让我们说我的控制器中的数据看起来像这样。
Array([Father_id] => 1 [Children] => Array([0] => John [1] => Peter [2] => Michael))
我将上面的数据传递给我的模型以向右插入,但我必须以一种方式对其进行重组,我可以将其发送到我的数据库进行插入。
foreach($data as $row){
for($temp = 0; $temp < count($data['Child_name']); $temp++){
$query[$temp] = array('Father_id' => $data['Father_id'], 'child_name' => $row[$temp]);
}
}
所以现在它看起来像这样,
Array([0]=>Array([Father_id] => 1 [Child_name] => John)[1]=>Array([Father_id] => 1 [Child_name] => Peter)[2]=>Array([Father_id] => 1 [Child_name] => Michael))
我理解如何插入这个,我只需要做另一个foreach循环,或者我可以删除$temp
中的$query[$temp]
,而是在该循环中放入一个插入查询。 / p>
我的问题是我怎么知道每个插入都是成功的,除了检查数据库之外,我想有一个return语句,如果它只有一个插入,那么如果它成功返回1。
还有更好的方法可以进行多次插入吗?
更新:
经过一些必要的休息后,我回来做了一些改变。
这是我的模特功能:
public function insert_children($data){
foreach($data['child_name'] as $row){
$query = array('father_id' => $data['father_id'], 'child_name' => $row);
$result = $this->db->insert('children',$query);
}
//return something here
}
必须将某些东西还给控制器吗?例如,如果插入成功与否,我想返回。那么在codeigniter中是否有任何已经制作的功能呢?或者我必须自己做。
例如,我可以在每次插入成功时创建一个$temp
变量以包含增量值,并在循环结束时将其与count($data['children'])
因此,如果有3个孩子,如果我用1 $temp = 1;
答案 0 :(得分:1)
插入多个数据的一般方法
$data = array(
array('father_id'=> 'id', 'child_name' => 'Unni' ),
array('father_id'=> 'id', 'child_name' => 'Kuttan' ),
//...
);
$this->db->insert('mytable', $data);
答案 1 :(得分:0)
您可以在每个循环项上使用affected_rows()
函数来检查是否插入了数据,并仅针对未插入的数据返回错误消息:
foreach($data as $row) {
for($temp = 0; $temp < count($data['Child_name']); $temp++){
// note that I remove [$temp] below
$query = array('Father_id' => $data['Father_id'], 'child_name' => $row[$temp]);
$this->db->query($query);
if($this->db->affected_rows() == 0) // data not inserted, return error message
{
$error[] = $row[$temp];
}
}
}
// shows error if one or more child name is not inserted
if (isset($error)) {
foreach ($error as $child_name) {
echo $child_name . ' is not inserted';
}
}