2017-10-28 73 views
3

我有兩個表productsshipments和數據透視表product_shipment與字段product_id and shipment_no。在數據透視表中,可以有一個貨號,例如。 #4562包含2個或更多產品。這是我想要實現的。基於ID插入多個項目 - Laravel

現在這是我的代碼如何工作。當我選擇產品hammer時,我可以檢索到hammer的編號。當我選擇另一種產品的編號screwdrivers時,它會替換hammer的編號,而不是同時存儲這兩個編號。

插入我的資料後,我想到的這個東西在我的透視表

產品表

product_id name 
    1   hammer 
    2   screwdriver 

貨量表

shipment_no courrier   
4562   MaerskLine 

督促追捧uct_shipment - 透視

shipment_no  product_no 
    4562    1 
    4562    2 

這是我我選擇我的產品複選框

HTML

<input onclick="return productSelected(this)" type="checkbox" 
id="{!! $product->id !!}" name="{!! $product->name !!}" /> 

我如何選擇取回自己的產品ID,當我選擇一個複選框

JS

function productSelected(product) 
{ 

    $(".panel").append(
    '<input type="text" value='+product.id+' " id="product_id" name="product_id" />' 

} 

我如何將數據保存到我的數據庫

控制器

$product_id = Input::get('product_id'); 
     $product_selected = Product::all()->where('id',$product_id)->first(); 

     $shipment_details = new Shipment(array(
      'shipment_no' => $request->get('shipment_no'), 
      'courrier' => $request->get('courrier'), 


     )); 

     $product_id->shipments()->save($shipment_details); 

貨物模型

public function products() 
    { 
     return $this->belongsToMany('App\Product') 
     ->withTimestamps(); 
    } 

產品型號

public function shipments() 
    { 
     return $this->belongsToMany('App\Shipment') 
     ->withTimestamps(); 
    } 

我怎樣才能得到我所選擇的產品的所有ID的,也有它看起來像什麼,我在我的pivot table感謝您的幫助

+0

你有沒有模型之間的關係 – Maraboc

+0

@Maraboc是的,我確實有模特的關係。它是一個多對多的關係 – XamarinDevil

+0

你可以添加兩個模型的代碼嗎? – Maraboc

回答

2

第一個變化的輸入名字是這樣的:

function productSelected(product) 
{ 

    $(".panel").append(
    '<input type="text" value='+product.id+' " id="product'+product.id+'" 
    name="products[]" />' 

} 

你應該得到陣列產品,現在在你的控制器的所有選擇的IDS。所以,你可以做這樣的事情:

$shipment_details = new Shipment(array(
     'shipment_no' => $request->get('shipment_no'), 
     'courrier' => $request->get('courrier'), 
)); 
$shipment_details->save(); 
$shipment_details->products()->sync($request->get('products')); 

你當然應該有ProductmanyToMany關係在您的Shipment模型。

+0

哦,那很簡單。非常感謝你 – XamarinDevil