【问题标题】:Id naming convention in LaravelLaravel 中的 ID 命名约定
【发布时间】:2015-01-27 21:04:40
【问题描述】:

在最近的一个项目中,我有一个自定义 ID 名称用于我的一个表,即用户表(它被称为 user_id 而不是简单的 id)。

当我尝试向其中插入数据时,出现以下错误:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: update users set active = 1, code = , updated_at = 2015-01-20 21:28:14 where id is null)

我通过将表的 id 列重命名为 id 解决了这个问题,因此符合 Laravel 的偏好。

但是,如果我在使用 Laravel 时绝对必须在任何给定表上使用自定义 id 名称,那么解决此问题的最佳解决方案/变通方法是什么?

【问题讨论】:

    标签: php mysql laravel eloquent fluent


    【解决方案1】:

    来自文档:

    http://laravel.com/docs/4.2/eloquent

    注意:Eloquent 也会假设每个表都有一个主键 名为 id 的列。您可以定义一个 primaryKey 属性来覆盖它 惯例。同样,您可以定义一个连接属性来覆盖 使用时应使用的数据库连接的名称 模型。

    因此,在您的模型中,您只需添加:

    protected $primaryKey = 'user_id';
    

    【讨论】:

      猜你喜欢
      • 2017-05-30
      • 2019-01-19
      • 1970-01-01
      • 2015-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-31
      相关资源
      最近更新 更多