I have 3 Models in My Laravel App like Employee , Salary and Title. Employee Model one to Many Relationship with both Salary and Title Models. Now I need update data using EmployeeController updateEmployee function EmployeeController
public function updateEmployee(Request $request, $id) {
$employee = Employee::find($id);
$title = $employee->titles()->update($request->all());
$salary = $employee->salaries()->update($request->all());
if(is_null($employee)) {
return response()->json(['message' => 'Employee not found'], 404);
}
$employee->update($request->all());
return response($employee, 200);
}
and my api route is following
Route::put('updateEmployee/{id}','App\Http\Controllers\EmployeeController@updateEmployee');
Employee Model
public function titles(): HasMany
{
return $this->hasMany(Title::class, 'emp_no');
}
public function salaries(): HasMany
{
return $this->hasMany(Salary::class, 'emp_no');
}
}
Salary Model
public function employee(): BelongsTo
{
return $this->belongsTo(Employee::class, 'emp_no');
}
Title Model
public function employee(): BelongsTo
{
return $this->belongsTo(Employee::class, 'emp_no');
}
I can update Title or Salary Tables separately. but when I set both same time like
$title = $employee->titles()->update($request->all());
$salary = $employee->salaries()->update($request->all());
it is encounting following error
Illuminate\Database\QueryException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'salary' in 'field list' (SQL: update titlessettitle= engineer,salary= 58000 wheretitles.emp_no= 2 andtitles.emp_no is not null) in file F:\2023\code\2023\api\vendor\laravel\framework\src\Illuminate\Database\Connection.php on line 760
Illuminate\Database\QueryException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'salary' in 'field list' (SQL: update titlessettitle= engineer,salary= 58000 wheretitles.emp_no= 2 andtitles.emp_nois not null) in file F:\2023\code\2023\api\vendor\laravel\framework\src\Illuminate\Database\Connection.php on line 760