【问题标题】:Laravel 5.6: Multiple primary key defined errorLaravel 5.6:多个主键定义错误
【发布时间】:2019-07-07 13:42:13
【问题描述】:

我创建了这个迁移脚本,但它给出了以下错误。如果我将另一列的数据类型更改为字符串或其他内容,它不会给出任何错误。如何解决这个问题?

    Schema::create('incidents', function (Blueprint $table) {
        $table->string('id');
        $table->primary('id');
        $table->unsignedInteger('user_id', 255);
    });

SQLSTATE[42000]:语法错误或访问冲突:1068 定义了多个主键(SQL:alter table incidents add primary key incidents_id_primary(id))

SQLSTATE[42000]:语法错误或访问冲突:1068 定义了多个主键

编辑

因为没有任何工作,我将这个 user_id 创建移动到另一个迁移脚本。现在它仍然无法运行第二个迁移脚本。给出这个错误。

语法错误或访问冲突:1068 定义了多个主键(SQL:alter table incidents add user_id int unsigned not null auto_increment 主键)

看来,如果主键不是整数,那么 laravel 会尝试将下一个整数列设为主键!!!

所以我的第一个脚本是,

 public function up()
 {
     Schema::create('incidents', function (Blueprint $table) {
         $table->string('id')->primary();
     });
 }

第二个脚本是,

public function up()
{
   Schema::table('incidents', function($table) {
     $table->unsignedInteger('user_id', 255);
   });
}

【问题讨论】:

  • 你不能有 2 列具有相同名称 $table->string('id'); $table->primary('id'); 将其更改为类似 $table->string('string_id'); $table->primary('id');
  • $table->string('id'); $table->primary('id');只使用一个
  • 为什么要将 id 作为字符串而不是仅使用整数作为主字符串?
  • 你能发布这个表的其他迁移吗? - @SameeraK
  • @SameeraK - 您是否尝试删除 $table->unsignedInteger('user_id'); 上的第二个参数

标签: php laravel


【解决方案1】:

更新

把它变成这样:

Schema::create('incidents', function (Blueprint $table) {
     $table->string('id')->primary();
     $table->unsignedInteger('another_column');
});

别忘了添加你的模型

protected $primaryKey = 'id';
public $incrementing = false; //If you dont want the auto-increment

问题

laravel docs

unsignedInteger(string $column, bool $autoIncrement = false)

您使用的函数接收一个布尔值作为参数,并且数字 255 被解释为真。我认为数据库使 autoIncrement 成为primary_key

【讨论】:

  • @SameeraK 这样试试
  • 是的,你是对的。唯一的问题是括号中的数字。它是如此奇怪的错误。
  • @SameeraK 我添加了一个解释,我希望它可以减轻你的一天=)
猜你喜欢
  • 2018-12-18
  • 2020-05-10
  • 2021-10-30
  • 2019-03-25
  • 2020-08-17
  • 1970-01-01
  • 2014-12-08
  • 1970-01-01
  • 2020-07-19
相关资源
最近更新 更多