如何将数据插入表中,然后使用最后保存的ID插入到其他表中

时间:2019-03-29 09:47:25

标签: laravel eloquent foreign-keys

public function postBomCopy(Request $request){ 

   $bom_id = $request->bom_id;       

   $total  = $request->total_cost;

   //insert the bom name first to get the new bom_id
   $bom = new Bom();
   $bom->cost=20;
   $bom->name=$request->bom;        
   $bom->save();        

    //get the new BOM DETAILS
   $new_bom_id = Bom::where('name', $bom->name)->orderBy('id', "DESC")
    ->first();        
   $n_bom_d = $new_bom_id->id; 

   foreach ($request->item as $key=> $v) { 
    $bom_new_id = new Bom_list();
    $bom_new_id ->bom_id = $n_bom_d;

    $data = array(
                 'item_id' => $request->item[$key],
                 'qty' => $request->item[$key],
                 'unit_cost' => $request->item[$key],
                 'total_cost' => $request->item[$key]
             );

   $bom_copy = $bom->bomList()->save($data); 
  } 


 Session()->flash('success','BOM successfully copied');
 return redirect()->back();
}

这是我得到的错误。

  

Symfony \组件\调试\异常\ FatalThrowableError(E_RECOVERABLE_ERROR)   传递给Illuminate \ Database \ Eloquent \ Relations \ HasOneOrMany :: save()的参数1必须是Illuminate \ Database \ Eloquent \ Model的实例,已给定数组,在C:\ xampp \ htdocs \ PrimeCartonInventory \ app \ Http \ Controllers中调用663行上的\ UsersController.php

3 个答案:

答案 0 :(得分:1)

要解决给定的错误,您应该传递Bom_list雄辩的对象。

正确方法:$ bom_copy = $ bom-> bomList()->保存(新Bom_list($ data));

当调用save()方法时,您将得到最后一个ID

//insert the bom name first to get the new bom_id
   $bom = new Bom();
   $bom->cost=20;
   $bom->name=$request->bom;        
   $bom->save();
   dd($bom->id); // will get the id of bom object u inserted in db

另一种好方法是将所有数据存储在集合中,然后一次插入db中。

   $bom = new Bom();
   $bom->cost=20;
   $bom->name=$request->bom;        
   $bom->save();        

   $bom_list_collection = collect();

   foreach ($request->item as $key=> $v) { 
     $data = array(
                 'bom_id' => $bom->id,
                 'item_id' => $request->item[$key],
                 'qty' => $request->item[$key],
                 'unit_cost' => $request->item[$key],
                 'total_cost' => $request->item[$key]
             );
     $bom_list_collection ->push(new Bom_list($data));
   } 
   $bom_copy = $bom->bomList()->saveMany($data);

引用链接:https://laravel.com/docs/5.8/eloquent-relationships#one-to-many

答案 1 :(得分:0)

最后插入Bom表的ID。

$n_bom_d = $bom->id;

答案 2 :(得分:0)

您应该将数组编码为字符串,然后尝试保存

foreach ($request->item as $key=> $v) { 
    $bom_new_id = new Bom_list();
    $bom_new_id ->bom_id = $n_bom_d;

    $data = array(
                 'item_id' => $request->item[$key],
                 'qty' => $request->item[$key],
                 'unit_cost' => $request->item[$key],
                 'total_cost' => $request->item[$key]
             );

   $data_new=json_encode($data);
   $bom_new_id->bom_list=$data_new;
   $bom_copy = $bom_new_id->save(); 
  }