问题
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');
回答1:
It is not implemented to do so. However, I found this over at the Laravel Forums:
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.
回答2:
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->count() + 1;
});
}
If you want disable autoincrementing add this at the beginning of the model file:
public $incrementing = FALSE;
回答3:
The current answer does not work, auto-incrementing columns must be primary keys. I recommend using firstOrCreate
when inserting to get the same level of uniqueness (provided you still want an auto-incrementing key available).
来源:https://stackoverflow.com/questions/42929776/how-to-set-auto-increment-into-non-primary-key