mybizna/automigrator

在 Laravel 模型内声明数据库迁移和工厂定义。

24.2.002 2024-04-04 11:51 UTC

README

此包允许您在 Laravel 模型内声明数据库迁移和工厂定义。

运行 automigrator:migrate 命令会自动将您在 migration 方法中做出的任何更改应用到数据库中,通过 Doctrine DBAL。如果您使用 HasNewFactory 特性和 definition 方法,它将使用 definition 方法中返回的数组进行播种,当使用 -s 选项时。

automigrator:migrate 命令还会先运行基于文件的(传统)Laravel 迁移,然后运行模型方法迁移。如果您需要按特定顺序运行基于模型的迁移,可以在模型中添加一个具有整数值的 $migrationOrder 属性(默认为 0)。

安装

使用 Composer 需求此包

composer require mybizna/automigrator

用法

使用 HasNewFactory 特性,并在模型中声明 migrationdefinition 方法

use Faker\Generator;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Schema\Blueprint;
use Mybizna\Automigrator\Traits\HasNewFactory;

class MyModel extends Model
{
    use HasNewFactory;

    protected $guarded = [];
    protected $migrationOrder = 1; // optional

    public function migration(Blueprint $table)
    {
        $table->id();
        $table->string('name');
        $table->timestamp('created_at')->nullable();
        $table->timestamp('updated_at')->nullable();
    }

    public function definition(Generator $faker)
    {
        return [
            'name' => $faker->name(),
            'created_at' => $faker->dateTimeThisMonth(),
        ];
    }
}

命令

迁移

migration 方法中的更改应用到数据库中

php artisan automigrator:migrate {--f|--fresh} {--s|--seed}

使用 -f 选项进行全新迁移,并/或使用 -s 选项运行种子文件。

创建模型

创建包含 migrationdefinition 方法的模型

php artisan automigrator:model {name} {--r|--resource}

使用 -r 选项同时创建模型的 Laravel Nova 资源。

创建 Nova 资源

创建不带所有注释的 Laravel Nova 资源

php artisan automigrator:resource {name} {--m|--model}

使用 -m 选项同时创建 Nova 资源对应的模型。