【问题标题】:Laravel: Once Migrating, It doesn't Create Custom Primary Key Column into MySQLLaravel:一旦迁移,它不会在 MySQL 中创建自定义主键列
【发布时间】:2018-07-23 09:36:50
【问题描述】:

问题是:我正在尝试为我的表Users 生成一个非常简单的自定义primary key(通过覆盖函数getKey())。当我迁移表时,它说:

SQLSTATE[42000]: Syntax Error or Acccess Violation: 1072 Key Column 'uid' Doesn't Exist in Table (SQL: Alter Table 'users' Add Primary Key 'users_uid_primary'('uid'))

提前感谢您的建议和更正。

编辑:迁移后,我的表在 MySQL 中创建,但没有主键列(在本例中为“uid”)。

架构:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->primary('uid');
        $table->string('username');
        $table->string('password');
        $table->timestamps();
    });
}

型号:

class User extends Model
{
    protected $primaryKey = 'uid'; //emphasize that the primary key isn't 'id'
    protected $keyType = 'string'; //p.k. holds string values
    public $incrementing = false; //then p.k. must not auto increment it
    public $timestamps = false; //no need for this one

    public function getKey() {

        return "u".rand(1000, 9999)."r"; //return something like 'u2548r'

    }
}

【问题讨论】:

    标签: laravel model eloquent artisan-migrate


    【解决方案1】:

    您必须实际创建该字段...您将一个不存在的字段 uid 设置为主键。

    您需要将字段定义为某种类型并将其添加到表中。 Blueprint@primary 正在设置索引(一般而言)而不是创建字段。

    【讨论】:

      【解决方案2】:

      您必须先在迁移中创建该字段:

      $table->string('uid')->primary();
      

      然后在你的模型类中设置它

      class User extends Model
      {
          protected $primaryKey = 'uid';
      
          ...
      
      }
      

      【讨论】:

        猜你喜欢
        • 2021-12-31
        • 2018-12-30
        • 2011-09-18
        • 2018-01-29
        • 1970-01-01
        • 2017-05-25
        • 2017-05-07
        • 2019-06-16
        • 2020-05-10
        相关资源
        最近更新 更多