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

标签 php mysql laravel eloquent

考虑以下表:personemployee,通过 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();

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

如果你想返回 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/

相关文章:

laravel - 注册成功后显示信息

php - Laravel Gmail : Expected response code 250 but got code "535",,消息为“535-5.7.8 用户名和密码未被接受。在 535 5.7.8 了解更多信息

php - Symfony Doctrine DQL 在实体管理器中找不到 createQuery

php - 如何将 PHP 中的 IP 地址作为二进制字符串进行比较?

php - 如何使用 laravel 处理 mysql 中的大型更新查询

php - 如何为 PHP $_GET 数组查询 MySQL 数据库

php - '<?=' 与 'echo' 相同吗?

php - Mysql在缺少html图像时创建双插入

php - 如何使用php统计搜索结果

PHP 购物车与 Laravel - 数量问题