3

I have 2 table products and variants, with a hasMany relationship, the structure is below :

Product Model :

public function variants()
{
   return $this->hasMany(Variant::class);
}

Variant Model :

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

Product Table :

|     id          name            image          manufacturer
|     1           T-Shirt         t-s.jpg        docomo      
|     2           Short Skirt     s-skirt.jpg    docomo  

Variant Table :

|     id     product_id      name       price    sku       quantity
|     1         1             S          30      ts-s       100
|     2         1             M          32      ts-m       100
|     3         1             XL         35      ts-xl      100
|     4         2             S          23      sk-s       100
|     5         2             M          25      sk-m       100
|     6         2             XL         28      sk-xl      100

I can save data on Variant model (child table) from Product model as :

public function store(Request $request)
{       
    $q = new Product;
    $q->name = $request->name;
    $q->save();
    // Below child table
    $q->variants()->createMany($request->variant);
}

I can store data, but the problem is that, how can I update child table? [It can be create, update or delete] I tried with sync() method, but didn't work. Its for manyToMany relationship.

public function update(Request $request)
{       
    $q = Product::findOrFail($request->id);
    $q->name = $request->name;
    $q->save();
    // Below child table update
    // $q->variants()->sync($request->variant); // not worked
}

sync() works in manyToMany relationship. I need the same for hasMany relationship.
How can I do that?

1 Answers1

0

Unfortunately there is no sync method for hasMany relations. It's pretty simple to do it by yourself. You can simple delete the rows and insert them all again.

public function update(Request $request, Product $product)
{       
    $product->update(['name' => $request->name]);
    // Below child table update
    $product->variants()->delete();
    $product->variants()->sync($request->variant);
}
MrEduar
  • 1,784
  • 10
  • 22
  • 1
    Don't do it this way because in the future you may need to store pivot data. – STA Aug 19 '20 at 13:09
  • If he needs to save additional data in the pivot table he can simply pass an array in the sync method with the additional information. This is not a problem and would be a feature that you are not sure will be added. – MrEduar Aug 19 '20 at 14:27