Laravel - 更新关系表中的动态字段

时间:2018-03-12 09:15:29

标签: php laravel laravel-5 eloquent

我有两张表汽车功能,其中汽车和功能有一对多关系。

汽车表格包含IDName列。功能表包含IDCarIDNameFeat Image

当我更新详细信息时,Cars表更新的功能表未更新。

Cars.php

public function features() {
    return $this->hasMany(Features::class, 'cars_id');
}

Features.php

public function feat()
{
    return $this->belongsTo(Cars::class, 'cars_id');
}

Controller.php这样

更新方法

public function update(Request $request, $id)
{        
    $requestData = $request->all();
    $cars = Cars::findOrFail($id);
    $features = Features::with(['feat'])->where('cars_id', $cars->id)->get();

    if($cars->update($requestData))
        {
            if ($request->hasFile('feat_img')) 
            {
                $file = $request->file('feat_img');
                $rules = array('file' => 'required|mimes:png,gif,jpeg'); 
                $validator = \Illuminate\Support\Facades\Validator::make(array('file'=> $file), $rules);
                if($validator->passes()) 
                {
                    $name = $request->name;
                    for ($i=0; $i < count(request('name')); ++$i) 
                    {
                    $features->name = request('name')[$i];
                    $feat_img_name = uniqid() . '.' . $images[$i]->getClientOriginalExtension();
                    $images[$i]->move(public_path('/images/'), $feat_img_name);            
                    $features->feat_img = '/images/'.$feat_img_name;   
                }
             }
         }
    $cars->features()->update($features);
    session()->flash('message', 'Product updated successfully.');
    return redirect('/');
}

存储方法

public function store(Request $request, Cars $cars)
{
  $cars= new Cars;
  $cars->name= request('name');
  $cars->image= $image;

   if($cars->save())
    {
     $features= [];
       $images = $request->file('feat_img');
       $name = $request->name;

        for ($i=0; $i < count(request('name')); ++$i) 
        {
        $features= new Features;
        $features->name = request('name')[$i];
        $feat_img_name = uniqid() . '.' . $images[$i]->getClientOriginalExtension();
        $images[$i]->move(public_path('/images/'), $feat_img_name);            
        $features->feat_img = '/images/'.$feat_img_name;
        $cars->features()->save($features);
        }
session()->flash('message','Product successfully added.'); 
        return redirect ('/');
    }
}

Features Form

1 个答案:

答案 0 :(得分:1)

使用这样的更新:

$features=Features::findOrFail(id);
$features->field=$value;
$features->save();

希望这有效。