looking for some solutions? You are welcome.

SOLVED: Updating one-to-many relationships with updateOrCreate methods

scopeak:

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],
   ]);
}

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,
  ]);
}

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!



Posted in S.E.F
via StackOverflow & StackExchange Atomic Web Robots
Share:

No comments:

Recent