如何在新版本迁移中使用auto_increment include创建多个主键


How to create multiple primary key with auto_increment include in laravel migrations?

我刚开始使用Laravel。我在做迁移时遇到了一个问题。我的Schema是这样的

public function up()
{
    Schema::create('journal', function($table){
        $table->increments('id');
        $table->timestamp('journal_date');
        $table->string('no_ref',25);
        $table->string('acc_id', 10);
        $table->string('description', 100);
        $table->integer('debet')->default(0);
        $table->integer('kredit')->default(0);
        $table->primary(array('journal_date', 'no_ref', 'acc_id'));
    });
}

然后当运行PHP artisan migrate时,我得到一个错误

[Illuminate'Database'QueryException]                                                                                                                                                            
SQLSTATE[42000]: Syntax error or access violation: 1068 Multiple primary key 
defined (SQL: alter table `journal` add primary key 
journal_journal_date_no_ref_acc_id_primary(`journal_date`,   
`no_ref`, `acc_id`))    

我对drop primary做了一些建议,但这也会降低自动增量。我只是不知道怎么弄清楚。

我终于找到了答案。我刚刚使用了DB::语句,像这样

                DB::statement('ALTER TABLE  `journal` DROP PRIMARY KEY , ADD PRIMARY KEY (  `id` ,  `journal_date` ,  `no_ref` ,  `acc_id` ) ;');

我的问题解决了

auto-increment字段必须是一个键(例如,MySQL甚至不允许你定义一个auto_increment列,如果它不是一个键)。这可能就是为什么你不能简单地放下钥匙的原因。在删除之前为字段定义第二个键。(表->增量(id) ->();独特)。

    public function up() {
    Schema::create('journal', function($table) {
        $table->increments('id')->unique();
        $table->timestamp('journal_date');
        $table->string('no_ref', 25);
        $table->string('acc_id', 10);
        $table->string('description', 100);
        $table->integer('debet')->default(0);
        $table->integer('kredit')->default(0);
    });
    Schema::table('journal', function($table) {
        $table->dropPrimary('id');
        $table->primary(['journal_date', 'no_ref', 'acc_id']);
    });
}

我找到了这个解决方案,请跟进。创建主键的小更改

public function up()
{
//
    Schema::create('journal', function($table){
        $table->unsignedInteger('id');
        $table->timestamp('journal_date');
        $table->string('no_ref',25);
        $table->string('acc_id', 10);
        $table->string('description', 100);
        $table->integer('debet')->default(0);
        $table->integer('kredit')->default(0);
        $table->primary(array('id', 'journal_date', 'no_ref', 'acc_id'));
    });
}