根据数据库生成迁移文件
因为一些历史原因,早期没有用 migration
建表,或是项目重构等,所以导致 migration
文件无法保证数据库的完整性
现在将原有的 migration
文件全部删除,从数据库同步一份最新的 migration
-
安装
composer
扩展composer require --dev "xethron/migrations-generator"
-
配置,在
config/app.php
文件的providers
中添加如下两行
Way\Generators\GeneratorsServiceProvider::class,
Xethron\MigrationsGenerator\MigrationsGeneratorServiceProvider::class,
- 执行迁移命令
php artisan migrate:generate
此适用于 5.x,若是 5 以上,推荐使用 https://github.com/oscarafdev/migrations-generator
数据库迁移
生成迁移文件 php artisan make:migration create_users_table
运行迁移 php artisan migrate
回滚迁移:
回滚最后一次:php artisan migrate:rollback
回滚最后5次:php artisan migrate:rollback --step=5
回滚所有:php artisan migrate:reset
删除所有表并重新迁移:php artisan migrate:fresh
具体怎么创建表,看文档吧,此处不做过多介绍
添加字段等相关
//添加字段
Schema::table('users', function ($table) {
$table->string('shu')->nullable()->after('name')->comment('通过migration添加的字段');//新添字段在name字段之后
$table->string('xiao')->nullable()->after('name')->comment('通过migration添加的字段');
$table->string('yuan')->nullable()->after('name')->comment('通过migration添加的字段');
});
//修改字段默认值
Schema::table('users', function ($table) {
$table->string('shu')->default('666')->change();//可以修改字段的默认值
});
//更改字段属性
Schema::table('users', function ($table) {
$table->string('xiao', 50)->change();//修改name字段长度为50
});
//重命名字段
Schema::table('users', function ($table) {
$table->renameColumn('xiao', 'shuang');
});
//移除字段
Schema::table('users', function ($table) {
// $table->dropColumn('shu');
$table->dropColumn(['shu', 'xiao', 'yuan']);//移除多个字段
});