2016-11-09 89 views
2

My Dynamic form use blade template如何存儲從多個動態形式使用laravel

控制器代碼數據:

$productPrice=$request->only('unit_id','size_id','color_id','price'); 
     dd($productPrice); 

控制器DD輸出:

array:4 [▼ 
    "unit_id" => array:3 [▼ 
    0 => "3" 
    1 => "7" 
    2 => "1" 
    ] 
    "size_id" => array:3 [▼ 
    0 => "2" 
    1 => "1" 
    2 => "4" 
    ] 
    "color_id" => array:3 [▼ 
    0 => "1" 
    1 => "6" 
    2 => "9" 
    ] 
    "price" => array:3 [▼ 
    0 => "32000" 
    1 => "4280" 
    2 => "5655" 
    ] 
] 

如何存儲在PRODUCT_PRICE表使用laravel容易的數據辦法??

+0

告訴我你的表單域或告訴我你有哪些模型 – lewis4u

回答

1

在使用中繼器的形式中,通過這種方式,除非將表單數據轉換爲字符串(serialize())並將其存儲在'價格中,否則無法將數據存儲在產品的同一表中'在產品表格中排列,這是將數據存儲在數據庫中的非常糟糕的方式。

這種情況下的最佳做法是製作一張用於存儲產品不同價格的新表格,因此您的表格應該如下所示。

產品表:

| id | name  | more columns | created_at   | updated_at  | 
---------------------------------------------------------------------------- 
| 1 |"product1" |  0  |2016-01-31 00:27:16 |2016-01-31 00:27:16| 
| 2 |"product2" |  1  |2016-01-31 00:27:16 |2016-01-31 00:37:16| 
| 3 |"product3" |  0  |2016-01-31 00:27:16 |2016-01-31 01:47:04| 

產品價格表:

| id | product_id | unit | size | color | price |created_at| updated_at | 
---------------------------------------------------------------------------- 
| 1 |  1  | 0 | 3 | 2 | 421 |2016-01.. |2016-01.. | 
| 2 |  1  | 3 | 2 | 5 | 121 |2016-01.. |2016-01.. | 
| 3 |  1  | 4 | 4 | 1 | 531 |2016-01.. |2016-01.. | 

所以這樣一來,只要你想一個產品可以有許多的價格,那麼你所要做的唯一事情是在這些表格的模型中建立關係。

在產品模型,你可以添加:

public function prices() { 
    return $this->hasMany(ProductPrice::class, 'product_id'); 
} 

當然,你將不得不作出ProductPrice模式,使這種關係的工作和。

個人而言,我也想補充的子模型reation(價格模型),像這樣:

public function product() { 
    return $this->belongsTo(Product::class, 'product_id'); 
} 

UPDATE:

現在,你有這些模型,你可以創建一個新ProductPrice項目使用下面的代碼:

foreach($productPrice['unit_id'] as $k => $unit) { 
    $product->prices()->create([ 
     'unit' => $productPrice['unit_id'][$k] 
     'size' => (isset($productPrice['size_id'][$k])) $productPrice['size_id'][$k] ? : 0; 
     'color' => (isset($productPrice['color_id'][$k])) $productPrice['color_id'][$k] ? : 0; 
     'price' => (isset($productPrice['price'][$k])) $productPrice['price'][$k] ? : 0; 
    ]); 
} 

但正如你所看到的,這似乎是的foreach一個有趣的,這是因爲你是仙丁每個價格類型的陣列形式的數據,所以使代碼更清潔,您可以發送的形式排列是這樣的:

productPrice[][unit_id] 
productPrice[][size_id] 
productPrice[][color_id] 
productPrice[][price] 

所以,那麼你的foreach代碼看起來就像這樣:

$productPrices = $request->only('productPrice'); 

foreach($productPrices as $productPrice) { 
    $product->prices()->create([ 
     'unit' => $productPrice['unit_id'], 
     'size' => $productPrice['size_id'], 
     'color' => $productPrice['color_id'], 
     'price' => $productPrice['price'], 
    ]); 
} 
+0

爲了您的實物信息我的數據庫結構與您在此描述的相同。感謝您的幫助@ yohanan-baruchel –

+0

如何查看我的更新表單,使用組窗體刪除按鈕,就像我的表單圖片一樣(https://i.stack.imgur.com/Uxwxi.png) –

+0

對不起我買了我下面和你的questiion關於刪除按鈕..你想做什麼? –