我有3张桌子可购物。一个是购物车的购物表。第二是订单表。最后一个是ordersItem表。 (这里是所有订单。)我想将id从订单表插入到ordersItem表多个。它有效,但仅在ordersItem上添加一行。我在购物车中添加了更多产品,但是当我添加insertId时,它仅将一行和一种产品添加到ordersItem表中。如果我在没有insertId的情况下使用它,它将正常工作。(它将添加多行)。我该如何正确执行此操作?
控制器:
public function insert(){
$data = array (
"ordersItem" => json_encode($this->input->post("serviceId")),
"ordersCus" => $this->session->userdata('people_id'),
"ordersStatus" => $this->input->post("status"),
"ordersDate" => date('Y-m-d H:i:s'),
);
$this->db->insert("orders", $data);
$ordersId = $this->db->insert_id();
$cusId = $this->session->userdata('people_id');
$checkout = $this->service_model->checkout($cusId);
foreach ($checkout as $check) {
$data = array (
"ordersItemOrdersId" => $ordersId,
"ordersItemServiceId" => $check->shoppingServiceId,
"ordersItemEstateId" => $check->shoppingEstateId,
"ordersItemVehicleId" => $check->shoppingVehicleId,
"ordersItemPiece" => $check->shoppingPiece,
"ordersItemAmount" => $check->shoppingPrice,
);
$insert = $this->db->insert("ordersItem", $data);
if($insert) {
$this->db->where('shoppingCusId', $cusId);
$this->db->delete('shopping');
redirect(base_url("checkout"));
}else {
echo "Hata!";
}
}
}
答案 0 :(得分:1)
您需要将redirect(base_url("checkout"));
移动到foreach循环之外,因为它将运行循环迭代,然后重定向以防止添加更多的行。
伪代码示例:
foreach ($checkout as $check) {
...
}
redirect(...);
我还建议您使用事务:
$this->db->trans_start();
foreach ($checkout as $check) {
$data = array(
"ordersItemOrdersId" => $ordersId,
"ordersItemServiceId" => $check->shoppingServiceId,
"ordersItemEstateId" => $check->shoppingEstateId,
"ordersItemVehicleId" => $check->shoppingVehicleId,
"ordersItemPiece" => $check->shoppingPiece,
"ordersItemAmount" => $check->shoppingPrice,
);
$this->db->insert("ordersItem", $data);
}
$this->db->trans_complete();
if ($this->db->trans_status()) {
$this->db->where('shoppingCusId', $cusId);
$this->db->delete('shopping');
redirect(base_url("checkout"));
} else {
echo "Hata!";
}