Laravel 多个主键迁移失败

Laravel migration fails multiple primary keys

我正在尝试在 Laravel 中创建一个迁移,但它没有说我有多个主键。

public function up()
{
    Schema::create('spins', function (Blueprint $table) {
        $table->integer('rid', true, true);
        $table->bigInteger('pid');
        $table->integer('result');
        $table->integer('bet');
        $table->timestamps();
        $table->primary(array('rid', 'pid'));
    });
}

错误:

SQLSTATE[42000]: Syntax error or access violation: 1068 Multipleprimary key defined 
(SQL: alter table `spins` add primary key `spins_rid_pid_primary` (`rid`, `pid`))      

你的主键没有意义。

您正在将复合主键添加到自动递增列和另一列。自动递增列将始终是唯一的,因此您应该只将其作为主键。

如果您需要 pid 是唯一的,请将 rid 设置为主键并在 pid 上添加一个唯一键。

Schema::create('spins', function (Blueprint $table) {
    $table->increments('rid');
    $table->bigInteger('pid');
    $table->integer('result');
    $table->integer('bet');
    $table->timestamps();
    $table->unique('pid');
});

如果出于某种原因您确实需要主键来包含 ridpid,这似乎对我有用。

CREATE TABLE `spins` (
  `rid` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `pid` BIGINT(20) NOT NULL,
  `result` INT(11) NOT NULL,
  `bet` INT(11) NOT NULL,
  `created_at` TIMESTAMP NOT NULL,
  `updated_at` TIMESTAMP NOT NULL,
  PRIMARY KEY (`rid`, `pid`)
) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

一个 table 上不能有多个主键。您可以有一个复合主键,它是由两个或多个列组成的主键。显然 Blueprint does not support creating composite keys,因此如果您想使用复合键,则必须使用查询生成器。

否则您可以选择 pidrid 作为您的主键。

rid 的自动增量是问题所在(下行中的第二个参数)。

$table->integer('rid', true, true);

如果您使用 InnoDB 作为 MySQL 引擎,它不允许具有自动增量的复合主键。

但是如果你换成 MyISAM 引擎就可以了。

  1. $table->engine = 'MyISAM'; 添加到您的迁移。

  2. rid字段声明为普通整数列

  3. Laravel 不提供更改现有列的方法,因此您需要 运行 原始 SQL 查询:DB::statement('ALTER TABLE spins MODIFY rid INTEGER NOT NULL AUTO_INCREMENT');


public function up()
{
    Schema::create('spins', function (Blueprint $table) {
        $table->engine = 'MyISAM';
        $table->integer('rid')->unsigned();
        $table->bigInteger('pid');
        $table->integer('result');
        $table->integer('bet');
        $table->timestamps();
        $table->primary(array('rid', 'pid'));

        DB::statement('ALTER TABLE spins MODIFY rid INTEGER NOT NULL AUTO_INCREMENT');
    });
}