Updating one-to-many relationships with updateOrCreate methods

sco*_*eak 5 php laravel eloquent

My main model Tag has a one-to-many relationship with Product where one Tag can have many Products assigned to them via tag_id relationship on the DB.

On my edit view, I am allowing users to edit the tag products. These products can be added/edited/deleted on the form request.

Each product field on the form is picked up from a request() array. E.g: request('title'),request('price').

I have set $title[$key] as the request('title') array for example.

My thoughts next, was to loop through each of the products for this tag and updateOrCreate based on the request data. The issue here, is that there's no way of detecting if that particular product was indeed needing updated.

TagController - Update Product Model (One-to-Many)

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],
   ]);
}
Run Code Online (Sandbox Code Playgroud)

For the initial tag update, I have set an if statement which works great (albeit messy) for the main tag img.

TagController - Update Tag Model

//Update the tag collection
if($request->hasFile('img')) {
  $tag->update([
    'name' => $name,
    'hashtag' => $hashtag,
    'img' => $imgPub,
  ]);
} else{
  $tag->update([
    'name' => $name,
    'hashtag' => $hashtag,
  ]);
}
Run Code Online (Sandbox Code Playgroud)

Is there a better way to determine if the product fields were updated on the request?

Ideally I would like the user to be able to add/remove or edit products from the tag edit request, but not delete existing product images if they have not been updated. Thanks!

May*_*iya 4

根据我的观点,你走错了路。标签关系应该是多对多。

您必须检查sync()Laravel 在 ManyToMany 关系中的方法。请检查:https://laravel.com/docs/5.8/eloquent-relationships#many-to-many

注意:请根据您的业务逻辑添加代码。

产品.php

  public function products(){
    return $this->belongsToMany( 'App\Product', 'product_tags', 'tag_id', 'product_id');
  }
Run Code Online (Sandbox Code Playgroud)

标签.php

   public function tags(){
     return $this->belongsToMany( 'App\Tag', 'product_tags', 'product_id', 'tag_id');
  }
Run Code Online (Sandbox Code Playgroud)

产品控制器.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');
 }
Run Code Online (Sandbox Code Playgroud)