【发布时间】:2015-02-04 11:02:53
【问题描述】:
我有一个对象,我想使用 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);
所以我想在数据库中插入这些,在 Order-table 中插入 1 行,在 Orderline-table 中插入 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);
我不确定插入订单时会发生什么,因为订单表中没有名为 orderlines 的行。 会被忽略或导致错误吗?这是一个好方法还是我做错了?
【问题讨论】:
标签: php mysql codeigniter oop