【问题标题】:Laravel 4.2 replicate including child itemsLaravel 4.2 复制包括子项
【发布时间】:2015-03-03 13:44:35
【问题描述】:

我尝试复制行但没有结果,我得到的订单复制没有相应的项目。

ORDERS pk(id) auto increment
id       total       status       date
-----+-------------+-----------+-------------
118      899.58        2          2015-03-03 00:18:58
119      38.55         2          2015-03-03 00:18:58


ITEMS pk(order_id,product_id) corresponding items childs:
order_id    product_id    quantity
----------+-------------+----------
118         1115          82 
119         8965          12      /// ro replicate


$idnew = Order::find($idorder)->replicate()->save(); // create new OK
$idnewId = $idnew->id;/////obtain id of last insert  
$itemstemp = DB::table('item')->where('order_id', '=' ,$idnewId)->get();

           foreach($itemstemp as $itemte){
            DB::table('item')->insert(array(
                'order_id'   => $itemte->order_id, 
                'product_id' => $itemte->product_id,
                'quantity'   => $itemte->quantity
                )); 
            }

Response ErrorExceptionTying to get property of non-object 行 $idnewId = $idnew->id;

期望的输出:

ORDERS pk(id)
id       total       status       date
-----+-------------+-----------+-------------
118      899.58        2          2015-03-03 00:18:58
119      38.55         2          2015-03-03 00:18:58
120      38.55         2          2015-03-03 00:18:58

ITEMS pk(order_id,product_id) corresponding items childs:
order_id    product_id    quantity
----------+-------------+----------
118         1115          82 
119         8965          12  
119         2255          22
120         8965          12  
120         2255          22  

有什么建议

【问题讨论】:

    标签: php mysql laravel replicate


    【解决方案1】:

    save() 只是返回一个布尔值,如果保存是否有效。你应该做的是:

    $new = Order::find($idorder)->replicate();
    $new->save();
    $itemstemp = DB::table('item')->where('order_id', '=' ,$new->id)->get();
    // and so on...
    

    我也认为你的逻辑有点错误。这样的事情对我来说更有意义:

    $new = Order::find($idorder)->replicate();
    $new->save();
    $items = DB::table('item')->where('order_id', $idorder)->get();
    $newItems = [];
    foreach($items as $item){
        $newItems[] = [
            'order_id' => $new->id,
            'product_id' => $item->product_id,
            'quantity'   => $item->quantity
        ];
    }
    DB::table('item')->insert($newItems);
    

    【讨论】:

    • 谢谢 Luka,我试了一下并执行查询没有错误,但没有插入子项行
    • 你确定吗?请用我的答案仔细检查您的代码。因为replicate() 绝对应该返回一个对象(准确地说是模型实例)
    • 是的,对不起。我更改了一个错误拼写错误的变量。现在执行查询没有错误,但没有插入子项行
    • 因为你的逻辑是错误的。您正在通过新订单 ID 而不是旧订单 ID 查找商品。看看我编辑的答案。
    • 优秀。感谢您的理解
    猜你喜欢
    • 2018-03-08
    • 2023-04-08
    • 1970-01-01
    • 2015-05-31
    • 2012-05-06
    • 2014-05-10
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多