考虑以下表:person
和 employee
,通过 person_id
连接到 person。这个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)
查询是否不知道我正在使用的列?
最佳答案
更改 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
在一个结果查询中是多余的
如果你想返回 Employee 和 Person,只需访问关系对象(employee 是从路由模型绑定(bind)返回的)
public function show(Employee $employee) {
$person = $employee->person;
return view('employee.show', compact('employee', 'person'));
}
希望这有帮助
关于php - 如何在 Laravel 中查询自定义键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58474008/