[英]Updating one-to-many relationships with updateOrCreate methods
我的主要模型Tag
與Product
有一對多的關系,其中一個Tag
可以通過DB上的tag_id
關系tag_id
分配許多Products
。
在我的編輯視圖中,我允許用戶編輯標簽products
。 可以在表單請求中添加/編輯/刪除這些產品。
表單上的每個product
字段都從request()
數組中獲取。 例如: request('title'),request('price')
。
我已將$title[$key]
為request('title')
數組。
接下來我的想法是根據請求數據循環遍歷此tag
每個products
和updateOrCreate
。 這里的問題是,沒有辦法檢測特定product
是否確實需要更新。
TagController - 更新產品型號(一對多)
foreach($tag->products as $key => $product){
Product::updateOrCreate([
'id' => $product->id,
],
[
'title' => $title[$key],
'price' => $price[$key],
'detail' => $detail[$key],
'order' => $order[$key],
'tagX' => $tagX[$key],
'tagY' => $tagY[$key],
'thumb' => $img[$key],
]);
}
對於初始tag
更新,我設置了一個if
語句,它對主標簽img
起作用很好(盡管很麻煩)。
TagController - 更新標記模型
//Update the tag collection
if($request->hasFile('img')) {
$tag->update([
'name' => $name,
'hashtag' => $hashtag,
'img' => $imgPub,
]);
} else{
$tag->update([
'name' => $name,
'hashtag' => $hashtag,
]);
}
有沒有更好的方法來確定product
字段是否在請求中更新?
我非常希望用戶能夠添加/刪除或編輯products
從tag
編輯請求,但如果他們沒有被更新,不刪除現有的產品圖片。 謝謝!
按照我的觀點,你走錯了路。 標記關系應該是多對多。
您必須在ManyToMany關系中檢查Laravel的sync()
方法。 請查看: https : //laravel.com/docs/5.8/eloquent-relationships#many-to-many
注意:請根據您的業務邏輯添加代碼。
Product.php
public function products(){
return $this->belongsToMany( 'App\Product', 'product_tags', 'tag_id', 'product_id');
}
Tag.php
public function tags(){
return $this->belongsToMany( 'App\Tag', 'product_tags', 'product_id', 'tag_id');
}
ProductController.php
public function update(Product $products, Request $request){
//update the product
$products->update($request->all());
//attach new tags to the product
$products->tags()->sync($request->input('tag_list'));
return redirect('articles');
}
通常我會在前端做類似的事情
<div class="product">
<!-- For Products that may be edited -->
<input type="hidden" name="id" value={{$product->id??0}}>
<input type="hidden" name="action" value="update">
<input type="text" name="title" value={{$product->title}}>
...
</div>
<div class="product">
<!-- For New Products -->
<input type="hidden" name="id" value=0>
<input type="hidden" name="action" value="add">
<input type="text" name="title" value="New Title">
...
</div>
<div class="product">
<!-- For Deleted Products -->
<input type="hidden" name="id" value={{$product->id}}>
<input type="hidden" name="action" value="delete">
<input type="text" name="title" value="New Title">
...
</div>
使用javascript創建json(產品對象數組)有效負載,並將ajax請求發送到后端
[{'id':101,'title':'product 1','action':'update'},
{'id':102,'title':'product 2','action':'update'},
... ,
{'id':201,'action':'delete'},
{'id':202, 'action':'delete'},
... ,
{'id':0,'title':'new product 1','action':'add'},
{'id':0,'title':'new product 2','action':'add'}]
現在在后端,遍歷產品列表並檢查操作。 根據行動,采取必要步驟。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.