artesaos / migrator
为 Laravel 5.1+ 提供命名空间迁移
This package is auto-updated.
Last update: 2024-03-25 02:32:08 UTC
README
此包是 Laravel 默认数据库迁移的定制版本,它被设计用于在服务提供器上注册迁移并支持命名空间。
由于运行顺序基于您注册迁移的方式,因此没有时间戳预览。
警告
此包支持从 5.2 版本开始直到最新稳定版本的 Laravel。
安装
为了安装 Migrator,请在您的 Laravel 5.2+ 项目中运行以下命令:
composer require artesaos/migrator
安装包后,您现在可以将提供器注册到 config/app.php 文件中
'providers' => [ // other providers omitted. Migrator\MigrationServiceProvider::class, ]
并发布配置:使用
php artisan vendor:publish --provider="Migrator\MigrationServiceProvider"
从 v1.x 升级到 v2.0。
在 v1.x 中,此包使用与默认迁移引擎相同的表名。
在版本 v2 中,有一个单独的表用于跟踪迁移,默认为:migrator_table
如果您从 v1 升级,可以重命名 migrations
表为 migrator_table
或者 发布配置文件并将迁移表名设置为 migrations
。
两种方式都可行。
v2 与默认迁移并行工作,适用于那些想要命名空间迁移但已有许多迁移的项目。
用法
作为默认的 Laravel 迁移器,它具有所有原始命令,要列出所有可用选项,可以使用 php artisan
命令查看所有可用选项。
migrator Run the database migrations
migrator:fresh Drop all tables and re-run all migrations
migrator:install Create the migration repository
migrator:make Create a new migration file
migrator:refresh Reset and re-run all migrations
migrator:reset Rollback all database migrations
migrator:rollback Rollback the last database migration
migrator:status Show the status of each migration
创建迁移
为了生成一个空迁移,请向迁移器提供完整的类名,如下例所示。
php artisan migrator:make 'MyApp\MyModule\Database\Migrations\CreateOrdersTable' --create=orders
这将在正确的目录中创建一个迁移类,生成的文件与默认 Laravel 生成的文件略有不同。
<?php namespace MyApp\MyModule\Database\Migrations; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateOrdersTable extends Migration { /** * @var \Illuminate\Database\Schema\Builder */ protected $schema; /** * Migration constructor. */ public function __construct() { $this->schema = app('db')->connection()->getSchemaBuilder(); } /** * Run the migrations. * * @return void */ public function up() { $this->schema->create('orders', function (Blueprint $table) { $table->increments('id'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { $this->schema->drop('orders'); } }
要声明您的表字段,只需遵循常规的架构构建实践,此包在此处不进行任何不同的处理。
作为常规迁移器,您可以使用 --table
选项而不是 --create
选项来生成更新迁移而不是创建迁移。此外,您也可以不传递任何这些选项来创建一个空迁移。
注册迁移。
在您选择的任何服务提供器内部(通常在存储迁移的同一名空间中),您可以使用 Migrator\MigratorTrait
轻松注册迁移。
<?php namespace MyApp\MyModule\Providers; use Illuminate\Support\ServiceProvider; use Migrator\MigratorTrait; use MyApp\MyModule\Database\Migrations\CreateOrdersTable; use MyApp\MyModule\Database\Migrations\CreateProductsTable; class MyModuleServiceProvider extends ServiceProvider { use MigratorTrait; public function register() { $this->migrations([ CreateOrdersTable::class, CreateProductsTable::class, ]); } }