2015-03-03 112 views
0

我试图复制行但没有结果,我得到的订单复制没有相应的项目。Laravel 4.2复制包括子项目

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 
       )); 
      } 

响应ErrorExceptionTrying得到非对象 线$ 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 

任何想法,请

回答

0

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); 
+0

感谢卢卡,我尝试并执行查询没有错误,但没有插入子项行 – Userlaravel 2015-03-03 13:54:05

+0

你确定吗?请用我的答案仔细检查你的代码。因为'replicate()'应该肯定会返回一个对象(模型实例要精确) – lukasgeiter 2015-03-03 13:55:59

+0

是的,对不起。我改了一个错误拼写错误的变量。现在执行查询没有错误,但没有插入子项行 – Userlaravel 2015-03-03 14:00:58