我一直想弄清楚如何更新我的hasMany關係模型。我可以輕鬆創建新的關係,但是當我嘗試更新我的關係模型時,它不起作用? laravel push()方法是否仍然有效?任何人都可以幫忙嗎?例如,我想更新我的控制器中與我的產品表相關的分類表。我有下面的代碼片段::如何更新Laravel hasMany Relationship Models?
Product.php
class Product extends Model
{
protected $fillable = [
'product_category', 'product_subcategory', 'product_name',
'product_price', 'product_id', 'product_description', 'product_image'
];
protected $primaryKey = 'product_id';
public $incrementing = false;
public function addTaxonomiesToProduct()
{
return $this->hasOne('App\Taxonomies', 'product_id', 'product_id');
}
}
Taxonomies.php
class Taxonomies extends Model
{
protected $fillable = ['product_category', 'product_subcategory'];
protected $primaryKey = 'product_id'; // or null
public $incrementing = false;
public function product()
{
return $this->belongsTo(Product::class);
}
}
EditProductController.php
class EditProductController extends Controller
{
public function update(Request $request, Product $product)
{
$product_size = array();
foreach ($request->product_size as $key => $value)
{
array_push($product_size,$value);
}
$product->update([
'product_name' => $request->product_name,
'product_price' => $request->product_price,
'product_description' => $request->product_description,
'product_size' => serialize($product_size),
'product_image' => $product_image_path,
]);
/**
* Go the products table,
* Get the product based off its product_id,
* and then update this products taxonomy
**/
$taxonomies = Product::find($product->product_id);
$taxonomies->addTaxonomiesToProduct->product_subcategory = "Mens Shoes";
$taxonomies->push();
}
}
****更新發布已解決**** 通過將我的產品表中hasMany()更改爲hasOne(),我的分類表正確更新。
@ Ross Wilson,非常感謝你的縮進那對我來說!!!! –
產品是否意味着有一個「分類法」,或者它可以有更多? –
@ Ross Wilson,產品可以有多個分類標準 –