Updating One to many relation in laravel 5.3

两盒软妹~` 提交于 2019-12-20 04:37:09

问题


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


来源:https://stackoverflow.com/questions/43109293/updating-one-to-many-relation-in-laravel-5-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!