如何在Laravel中查询自定义键?

时间:2019-10-20 14:29:52

标签: php mysql laravel eloquent

考虑此表:person与人相连的​​employeeperson_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)

查询是否不知道我正在使用的列?

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();

orderByfirst在一个结果查询上是多余的

如果您想将Person带回Employee,则只需访问关系对象(员工从路由模型绑定中返回)

public function show(Employee $employee) {
    $person = $employee->person;
    return view('employee.show', compact('employee', 'person'));
}

希望这会有所帮助