Updating One to many relation in laravel 5.3

2019-03-04 01:52发布

问题:

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.

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