【问题标题】:Change id column name on Laravel 6.5.1在 Laravel 6.5.1 上更改 id 列名称
【发布时间】:2020-03-20 03:06:03
【问题描述】:

我在 Laravel 6.5.1 中有一个模型用户。

class User extends Authenticatable
{
    use Notifiable;

    public $table = 'usuario';
    public $primaryKey = 'cif_usu';
    public $incrementing = false;
    public $timestamp = false;

   //...
}

但是,当我尝试选择用户时,我收到以下错误:

SQLSTATE[42703]:未定义列:7 错误:列“id”不存在 LINE 1: select * from "usuario" where "id" = $1 limit 1 ^ (SQL: select * 来自 "usuario" 其中 "id" = 24 限制 1)

如何重命名 id 列?

编辑:

我变了:

public $primaryKey = 'cif_usu';

到:

protected $primaryKey = 'cif_usu';

结果是一样的

【问题讨论】:

标签: php laravel laravel-6


【解决方案1】:

将主键和表设置为受保护。

protected $table = 'usuario';

protected $primaryKey = 'cif_usu';

public $incrementing = false; //only if your primary key is an assignable field,not auto incremented

你可以使用模型作为

DB::table('usuario')->where('cif_usu',$cif_usu)->first();

DB::table('usuario')->find($cif_usu);

【讨论】:

    【解决方案2】:

    Eloquent 还会假设每个表都有一个名为 id 的主键列。你可以定义一个受保护的$primaryKey 属性来覆盖这个约定:

    /**
     * The primary key associated with the table.
     *
     * @var string
     */
    protected $primaryKey = 'key';
    

    阅读更多关于Laravel - Primary Keys

    【讨论】:

      【解决方案3】:

      $primaryKey 属性的可见性应为protected。我认为如果没有流量发生变化,您实际上并没有覆盖 Model 基类中的主键。

      如果不是这样,查看触发此查询的代码可能会很有用

      【讨论】:

        猜你喜欢
        • 2022-01-14
        • 1970-01-01
        • 1970-01-01
        • 2018-02-14
        • 2022-01-02
        • 2016-01-11
        • 2020-12-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多