Laravel迁移失败了多个主键

Maa*_*tje 6 migration primary-key laravel

我试图在Laravel中创建一个Migration但是它没有说我有多个主键.

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'));
    });
}
Run Code Online (Sandbox Code Playgroud)

错误:

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

Pᴇʜ*_*Pᴇʜ 8

自动增量rid是问题(下面一行中的第二个参数).

$table->integer('rid', true, true);
Run Code Online (Sandbox Code Playgroud)

如果您使用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');
    });
}
Run Code Online (Sandbox Code Playgroud)