【问题标题】:Insert nested objects into multiple tables将嵌套对象插入多个表
【发布时间】: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


    【解决方案1】:

    应该是:

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

    对于查询不成功的情况,您也可以使用rollback method

    【讨论】:

    • 真正的东西有更多的属性,帖子中的例子是为了简化它。
    • 关于“嵌套对象”。如果它在范围内,则可以读取它,但它是数组元素普通变量、对象属性或其他东西。我不明白为什么不将其解释为价值。
    猜你喜欢
    • 1970-01-01
    • 2018-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    • 2016-01-03
    相关资源
    最近更新 更多