Laravel Migration:当它不是主要时自动增加键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26693350/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:21:44  来源:igfitidea点击:

Laravel Migration: auto increment key when it is not primary

phpmysqllaravellaravel-4database-migration

提问by CarlosMaia

I'm trying to create a table with Laravel migrations but I'm having some trouble. I just need to create a table with a primary pair ('id' and 'revision'), being 'id' an auto increment. I can do it in MySQL, but I can't manage to do it with Laravel Migrations since increments() also set the field as primary. So far I have this:

我正在尝试使用 Laravel 迁移创建一个表,但遇到了一些问题。我只需要创建一个带有主要对(“id”和“revision”)的表,“id”是一个自动增量。我可以在 MySQL 中执行此操作,但我无法使用 Laravel Migrations 执行此操作,因为 increments() 还将该字段设置为主要字段。到目前为止,我有这个:

Schema::create('bibliographies', function(Blueprint $table)
    {
        $table->increments('id');
        $table->integer('revision');
        ...
        $table->timestamps();
        $table->softDeletes();
        $table->primary(array('id', 'revision'));
    });

Note: changing increments() method is not an option since it is Laravel core.

注意:更改 increments() 方法不是一个选项,因为它是 Laravel 的核心。

Thank you for your help in advance.

提前谢谢你的帮助。

回答by Joe

Just drop the primary keybefore you re-add it:

只需在重新添加主键之前删除主键

$table->dropPrimary( 'id' );
$table->primary( array( 'id', 'revision' ) );

回答by Abhishek Deshpande

 $table->unsignedInteger('id')->change();//will remove the auto increment
 $table->dropPrimary('id');//will remove primary constrain
 $table->unsignedInteger('revision') //add revision column
 $table->primary( array( 'id', 'revision' ) );//make them both primary
 $table->increments('id')->change()//add the auto increment constrain back