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

问题描述 投票:0回答:1

考虑该表:personemployee通过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)

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

考虑此表:人员和通过person_id与人员连接的员工。此person_id也是employee表的主键和外键。因此,在我的迁移中,我有这个:...

php mysql laravel eloquent
1个回答
2
投票

更改雇员模型中的主键

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');
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.