具有一个自动增量Laravel的多个主键

时间:2019-06-02 16:24:31

标签: composite-primary-key laravel-5.8

我必须使用Laravel将此数据库迁移到MySQL,但是看来我不能对自动增量元素使用多个主键。

 public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('user_id');
        $table->string('name');
        $table->string('surname');
        $table->string('email')->unique();
        $table->string('tel');
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });

    Schema::create('collections', function (Blueprint $table) {
        $table->unsignedBigInteger('user_id');
        $table->foreign('user_id')->references('user_id')->on('users');
        $table->bigIncrements('collection_id');

        $table->primary(['user_id', 'collection_id']);
        $table->string('title');
        $table->string('img_url');
        $table->timestamps();
    });

    Schema::table('collections', function (Blueprint $table) {
        $table->dropPrimary('collections_collection_id_fk_primary');
    });

    Schema::create('contents', function (Blueprint $table) {
        $table->unsignedBigInteger('collection_id');
        $table->foreign('collection_id')->references('collection_id')->on('collections');
        $table->bigIncrements('content_id');

        $table->primary(['content_id', 'collection_id']);
        $table->string('title');
        $table->string('author');
        $table->string('publisher');
        $table->string('pages');
        $table->string('google_id');
        $table->string('img_url');
        $table->timestamps();
    });


Schema::table('collections', function (Blueprint $table){
    $table->dropPrimary('contents_content_id_fk_primary');
});
}

我尝试使用dropPrimary,但是它不执行查询,因为它会在以下错误处停止:“ Illuminate \ Database \ QueryException:SQLSTATE [42000]:语法错误或访问冲突:1068多个主数据库定义的键(SQL:alter table collections添加主键collections_user_id_collection_id_primaryuser_idcollection_id))

你能帮我吗?

1 个答案:

答案 0 :(得分:1)

TLDR: 以下列定义已自动创建主键:

$table->bigIncrements('collection_id');

因此,您对$ table-> primary()的显式调用将尝试创建第二个主键。

好答案

我遇到了类似的问题。我在两列上有一个复合主键,这在我开始排队作业时会引起问题,因为框架仅序列化了模型的$ primaryKey(您不能在模型中将两列定义为$ primaryKey。因此,我添加了一个自动递增主键迁移列:

$this->bigIncrements('id')->primary();

这导致您收到错误消息。删除primary()调用后,它起作用了,我注意到主键已自动设置。 相反,我现在使用的是复合唯一键:

$table->unique(['column_a', 'column_b']);

我希望这对您有帮助。

相关问题