Laravel中不存在方法IlllightateSupportCollection::Save

2022-03-26 00:00:00 sql php mysql laravel laravel-8

我在控制器中使用联接的数据捕获视图中有一个下拉列表,但当我尝试保存记录时,收到以下错误。

Method IlluminateSupportCollection::save does not exist.

我已尝试将雄辩语句更改为

 $energy = DB::table('vehicleslog')->join('vehicle', 'vehicleslog.vehicle_id', '=', 'vehicle.id')->first();

而不是

$energy = DB::table('vehicleslog')->join('vehicle', 'vehicleslog.vehicle_id', '=', 'vehicle.id')->first();

但是,这会给我以下错误。

Call to undefined method stdClass::save()

有人知道正确的是什么吗?

控制器:

  public function index()
    {

        // $energy = Maintenance::orderBy('id', 'desc')->paginate(5);
        $energy = DB::table('vehicleslog')->join('vehicle', 'vehicleslog.vehicle_id', '=', 'vehicle.id')->get();
        $cars = Vehicle::get();
        $staff = Staff::all();
        return view('admin.vmaintenance', compact('energy', 'cars', 'staff'));
    }
    public function store(Request $request)
    {

        // $energy = new Maintenance;
        $energy = DB::table('vehicleslog')->join('vehicle', 'vehicleslog.vehicle_id', '=', 'vehicle.id')->first();
        $cars = Vehicle::all();
        $staff = Staff::get();
        $energy->staff_key = $request->input('staff_key');
        $energy->vehicle_id = $request->input('vehicle_id');
        $energy->log_dt = $request->input('log_dt');
        $energy->admin_time = $request->input('admin_time');
        $energy->driving_time = $request->input('driving_time');
        $energy->work_time = $request->input('work_time');
        $energy->jobcard_count = $request->input('jobcard_count');
        $energy->start_odo = $request->input('start_odo');
        $energy->end_odo = $request->input('end_odo');


        $energy->save();
        return redirect('/vmaintenance')->with('success', 'data added');
    }

查看:

<label>Select Vehicle</label>
                    <select name="vehicle_id" >
                        @foreach($cars as $car)
                        <option value="{{ $car->id }}">{{ $car['reg_number'] }}</option>
                @endforeach
                    </select>
                  
           
            

解决方案

急切加载:

$energy=VehicleLog::with(‘Vehicle’)->;First();

也:

  • 此变量从未在store()操作中使用:
$cars = Vehicle::all();
$staff = Staff::get();
  • 您可以使用fill()方法:
$energy->fill($request->only([
    'staff_key', 'vehicle_id', 'admin_time',
    'driving_time', 'work_time', // ...
]));

相关文章