自动生成迁移文件
迁移文件
介绍
大家在开发过程中有没有觉得写这个迁移代码很麻烦,还要去看一些文档规则
解决
1. 考虑到这些我们直接用可视化工具进行数据表创建
2. 通过命令逆向生成对应的迁移文件,我们以users表为例:
考虑到迁移文件比较多我们进行依据年份进行分目录存放
逆向生成迁移文件功能考虑到已经有现成的开发包”kitloong/laravel-migrations-generator”,就直接使用了
这个命令没有对数据表进行检查请注意不要重复生成
php artisan migrate:generate --tables=users --ignore --path=database/migrations/2021
3. 生成代码位置”database/migrations/2021”
4. 对应修改变更表结构的我们也可以通过可视化工具进行修改,获得sql命令后直接复制过来使用
- 这里注意文件名的命名迁移文件是顺序执行的对文件名的命名规则要按时间先后定义,如:”2020_12_07_091231_alert_users_table.php”
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AlertUsersTable extends Migration
{
protected $bindModel='App\Models\Order';
/** * Run the migrations. * * 返回: void */ public function up()
{ $model = new $this->bindModel();
$prefix = $model->getConnection()->getTablePrefix();
$connection = $model->getConnectionName()?: config('database.default');
DB::connection($connection)->statement("ALTER TABLE `".$prefix.$model->getTable()."`
MODIFY COLUMN `avatar` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '头像@sometimes|required|url' AFTER `password`;");
}
/** * Reverse the migrations. * * @return void */ public function down()
{ $model = new $this->bindModel();
$prefix = $model->getConnection()->getTablePrefix();
$connection = $model->getConnectionName()?: config('database.default');
DB::connection($connection)->statement("ALTER TABLE `".$prefix.$model->getTable()."`
MODIFY COLUMN `avatar` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT '' COMMENT '头像@sometimes|required|url' AFTER `name`;");
}}