将嵌套对象插入到多个表中


Insert nested objects into multiple tables

我有一个对象,我想使用 CodeIgniter/PHP 添加到 MySQL 数据库中。然而,问题是它也具有需要插入(或更新)的其他对象的数组。

我的意思的简化示例:

数据库中的表:

+----------+
| Order    |
+----------+
| - id     |
| - name   |
| - date   |
+----------+
+-------------+
| Orderline   |
+-------------+
| - orderId   |
| - productId |
| - amount    |
+-------------+

我要插入的对象示例:

$order->name = “John Doe”
$orderline1 = new stdClass();
$orderline1->productId = 1;
$orderline1->amount = 10;
$orderline2 = new stdClass();
$orderline2->productId = 2;
$orderline2->amount = 5;
$order->orderlines = array($orderline1, $orderline2);

所以我想将它们插入数据库中,订单表中的 1 行和订单行表中的 2 行。我正在使用CodeIgniter(因为我必须这样做)。我知道如何插入对象以及如何获取上次插入的 ID。但是我不确定嵌套对象,我还必须首先将 orderId 添加到所有订单行中。

到目前为止,我拥有的:

$this->db->insert('Order', $order); // no clue what will happen to the $order->orderlines doing this
$orderId = $this->db->insert_id(); // to get the id to add to the orderlines
// a loop to add the orderId
foreach($order->orderlines as $orderline){
    $orderline->orderId = $orderId;
}
// to insert the orderlines
$this->db->insert_batch('orderline', $order->orderlines);

我不确定插入订单时会发生什么,因为订单表中没有称为订单行的行。它会被忽略还是导致错误?这是一个好方法还是我做错了?

应该是:

$this->db->insert('Order', $order->name);

此外,对于查询失败的情况,也可以使用回滚方法。