考虑此表:person
与人相连的employee
和person_id
。此person_id
也是employee
表的主键和外键。因此,在我的迁移中,我有这个:
Schema::create('employees', function (Blueprint $table) {
$table->bigIncrements('person_id');
$table->foreign('person_id')->references('id')->on('persons')->onDelete('cascade');
});
我的show
方法就是这样
public function show(Employee $employee){
dd($employee->person_id);
$employee = Employee::where('person_id', $employee->person_id)->orderBy('employee_number', 'asc')->join('persons', 'employees.person_id', '=', 'persons.id')->first();
return view('employee.show', compact('employee'));
}
但是我遇到了这个问题:
Illuminate\Database\QueryException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from `employees` where `id` = 5 limit 1)
查询是否不知道我正在使用的列?
答案 0 :(得分:3)
更改Employee模型中的主键
class Employee extends Model
{
/**
* The primary key associated with the table.
*
* @var string
*/
protected $primaryKey = 'person_id';
public function person()
{
return $this->belongsTo('App\Employee', 'person_id', 'person_id');
}
}
然后使用find
Employee::find($employee->person_id)->with('person')->first();
orderBy
和first
在一个结果查询上是多余的
如果您想将Person带回Employee,则只需访问关系对象(员工从路由模型绑定中返回)
public function show(Employee $employee) {
$person = $employee->person;
return view('employee.show', compact('employee', 'person'));
}
希望这会有所帮助