【问题标题】:Laravel - Incorrect table definition; there can be only one auto column and it must be defined as a key"Laravel - 不正确的表定义;只能有一个自动列,并且必须将其定义为键”
【发布时间】:2021-07-21 08:57:51
【问题描述】:

在我的 Laravel-8 应用程序中,我得到了以下代码:

public function up()
{
    Schema::create('user_log_activities', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->bigInteger('user_id')->nullable()->unsigned();
        $table->string('log_url', 300)->nullable();
        $table->string('log_method', 20)->nullable();
        $table->string('log_type', 50)->nullable();
        $table->string('subject', 200)->nullable();
        $table->string('subject_hint', 20)->nullable();
        $table->integer('company_id', 11)->nullable();
        $table->string('id_address', 64)->nullable();
        $table->string('agent', 300)->nullable();
        $table->timestamps();
    });
}

问题出在这里:

$table->bigInteger('user_id')->nullable()->unsigned();

user_id 不是自动递增的,但是我收到了这个错误:

PDOException::("SQLSTATE[42000]: 语法错误或访问冲突:1075 表定义不正确;只能有一个 auto 列,它必须被定义为一个键")

我尝试了几种方法,但都不起作用

如何解决?

谢谢

【问题讨论】:

    标签: laravel


    【解决方案1】:

    问题是您使用整数的长度。 11 计为自动递增值

    $table->integer('company_id', 11)->nullable();
    

    从中删除长度

    $table->integer('company_id')->nullable();
    

    如果是外键,则与 user_id 相同

    【讨论】:

      【解决方案2】:
      $table->integer('company_id', 11)->nullable();
      

      替换为

      $table->integer('company_id')->nullable();
      

      【讨论】:

        【解决方案3】:

        如果user_id是外键,可以使用外键定义:

        https://laravel.com/docs/8.x/migrations#foreign-key-constraints

        public function up()
        {
            Schema::create('user_log_activities', function (Blueprint $table) {
                $table->bigIncrements('id');
                $table->foreign('user_id')->nullable()->references('id')->on('users');
            });
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-01-01
          • 2015-04-05
          • 2013-07-12
          • 1970-01-01
          • 2017-05-31
          • 2013-12-17
          • 1970-01-01
          • 2015-05-07
          相关资源
          最近更新 更多