2016-01-19 145 views
3

我想在Laravel中创建一个迁移,但它失败说我有多个主键。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`))  

回答

2

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'); 
    }); 
} 
+0

这似乎工作。非常感谢,我可以接受它作为答案。 – Maantje

0

你的主键是没有意义的。

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

如果您需要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; 
0

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

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

+1

'Blueprint'不支持复合主键,你不能让这些键之一自动递增。我通常使用'Blueprint'在数据透视表上执行复合主键,它工作正常。 – user3158900

+0

@ user3158900嗯,这是坏它不能自动增量:/虐待必须尝试另一种方式然后 – Maantje

+1

如果你真的需要这个主键,可能通过查询生成器,并可以通过原始SQL。 – user3158900