1

I want to update a one to many relationship. For example I have a model called Product

class Product extends Model
{
    protected $primaryKey = 'product_id';
    public $timestamps = FALSE;

    public function Size(){
        return $this->hasMany('App\Size');
    }

}

and a model called Size

class Size extends Model
{
    public $timestamps = FALSE;
    protected $fillable = ['product_id','size'];

    public function Product(){
        return $this->belongsTo('App\Product');
    }

here is my controller:

public function update(Request $request){
    for($i = 1; $i <= $sizeCounter; $i++){
        $selectedSize = "size_$i";

        if($request->$selectedSize){
            $array = ['size'=> $request->$selectedSize];
        }
    }

    $Size = Size::where('product_id' , $request->id)->update($array);
}

But what it is doing updating all the records of size with the selectedd product id to the last enterder size. I want to update all the sizes with the slected diffrent sizes not the last selected sizes

How to update the sizes of a particular product. Like many to many relations' sync method is there any way to update the records.

SUB0DH
  • 5,130
  • 4
  • 29
  • 46
Mutasim Fuad
  • 606
  • 2
  • 12
  • 31

1 Answers1

1

You override your $array in the loop. After the for loop, $array has possibly the last size.

In general, your query is correct, but it's about the place of execute. It should be like below:

if (isset($request->$selectedSize)) { // or is_int() ?
    $Size = Size::where('product_id', $request->id)->update(['size'=> $request->$selectedSize]);
}
schellingerht
  • 5,726
  • 2
  • 28
  • 56
  • 1
    Oh sorry i just did it in the last version overrided the array but did not corrected here. But i'v solveld it some how. Thanks for your appreciation. Hope i will be getting more help from you. :) – Mutasim Fuad Mar 30 '17 at 08:01
  • Is there any way to update the table with the new selected item and delete the old ones automatically. Lets say I had S.M,L i want to update with size M,L so i need to delete the S size entry from table. – Mutasim Fuad Mar 30 '17 at 09:47
  • I suppose you want to remove the relationship between `product` and `size`? In this case, you can use use `detach()` and `sync()` – schellingerht Mar 30 '17 at 09:57
  • Its sync( ) is giving me the BadMethodeCallException – Mutasim Fuad Mar 30 '17 at 11:27