laravel 如何将自动增量设置为非主键?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42929776/
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 15:37:48  来源:igfitidea点击:

How to set auto increment into non primary key?

laravellaravel-migrationslaravel-schema-builder

提问by Luiz

How would I set a database auto increment field that is not a primary key on the creation method?

如何在创建方法上设置不是主键的数据库自动增量字段?

The only way is using a raw query?

唯一的方法是使用原始查询?

DB::statement('ALTER TABLE table CHANGE field field INT(10)AUTO_INCREMENT');

DB::statement('ALTER TABLE table CHANGE field field INT(10)AUTO_INCREMENT');

回答by Niklas S.

It is not implemented to do so. However, I found this over at the Laravel Forums:

没有实现这样做。但是,我在Laravel 论坛上发现了这一点:

Schema::table('table', function(Blueprint $t) {
    // Add the Auto-Increment column
    $t->increments("some_column");

    // Remove the primary key
    $t->dropPrimary("table_some_column_primary");

    // Set the actual primary key
    $t->primary(array("id"));
});

This is not tested but should work. I am not sure about how Laravel calls their primary keys, maybe you have to check that first and adapt the dropPrimary()line in order to make it work.

这没有经过测试,但应该可以工作。我不确定 Laravel 如何调用它们的主键,也许您必须先检查并调整该dropPrimary()行以使其工作。

回答by insign

I do not feel safe doing some workaround at migrations, so I did this inside model file:

我觉得在迁移时做一些解决方法不安全,所以我在模型文件中做了这个:

/**
 *  Setup model event hooks
 */
public static function boot()
{
    parent::boot();
    self::creating(function ($model) {
        $model->field_here = $model->max('field_here') + 1;
    });
}

If you want disable autoincrementing add this at the beginning of the model file:

如果您想禁用自动递增,请在模型文件的开头添加:

public $incrementing = FALSE;

回答by Rowan Christmas

The current answer does not work, auto-incrementing columns must be primary keys. I recommend using firstOrCreatewhen inserting to get the same level of uniqueness (provided you still want an auto-incrementing key available).

当前答案不起作用,自动递增列必须是主键。我建议firstOrCreate在插入时使用以获得相同级别的唯一性(前提是您仍然需要一个可用的自动递增键)。