Lui*_*uiz 2 laravel laravel-migrations laravel-schema-builder
如何设置不是创建方法主键的数据库自动增量字段?
唯一的方法是使用原始查询?
DB::statement('ALTER TABLE table CHANGE field field INT(10)AUTO_INCREMENT');
没有实现这样做.但是,我在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"));
});
Run Code Online (Sandbox Code Playgroud)
这没有经过测试但应该有效.我不确定Laravel如何调用他们的主键,也许你必须首先检查它并调整dropPrimary()线路以使其工作.
我觉得在迁移时做一些解决方法并不安全,所以我在模型文件中做了这个:
/**
* Setup model event hooks
*/
public static function boot()
{
parent::boot();
self::creating(function ($model) {
$model->field_here = $model->max('field_here') + 1;
});
}
Run Code Online (Sandbox Code Playgroud)
如果您想禁用自动增量,请在模型文件的开头添加以下内容:
public $incrementing = FALSE;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5843 次 |
| 最近记录: |