gpt4 book ai didi

Laravel迁移使多个主键失败

转载 作者:行者123 更新时间:2023-12-04 13:58:42 25 4
gpt4 key购买 nike

我正在尝试在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'));
});
}

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

最佳答案

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

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

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

但是如果您更改为MyISAM引擎,则可以这样做。
  • $table->engine = 'MyISAM';添加到您的迁移中。
  • 声明rid字段为普通整数列
  • 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');
    });
    }

    关于Laravel迁移使多个主键失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34880277/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com