aldeebhasan/migration-mapper

本包旨在允许开发者通过构建模型来生成迁移文件

1.0.0 2024-02-19 20:03 UTC

This package is auto-updated.

Last update: 2024-09-27 06:30:11 UTC


README

从模型自动生成迁移文件

为什么

Laravel 应用程序最重要的和关键部分之一是迁移文件。每次您需要向表中添加单个列时,您都需要进入控制台,创建迁移文件,添加迁移命令,最后运行迁移。

此包将隐藏这些开销,您只需要定义模型蓝图,我们将自动处理一切。

安装

使用 composer 安装

composer require aldeebhasan/migration-mapper

安装后,运行以下代码以发布配置

php artisan vendor:publish --tag=migration-mapper-config

基本用法

假设您有一个名为 Product 的模型,具有以下三个参数 [id,name,description,category_id,visible] 如下所示

#[Table(
    name: 'x_models', // optional
    columns: [
        new Id(),
        new String_('name', length:255, default: "admin"),
        new Text('description', length:255, default: "admin"),
        new BigInteger('category_id', nullable: true, index: true, unsigned: true),
        new Enum('visible', ['off', 'on'], default: 'off', comment: 'status of the product'),
    ]
)]
class XModel extends Model
{
    protected $fillable = [
        'name', 'description', 'category_id'
    ]; 
}

每次您想要生成迁移文件时,您只需调用

php artisan mapper:generate

上述命令的结果将是

database
    migrations
        2024_02_19_1708369156_create_x_models_table_m.php

请注意,表的 name 参数是可选的。如果没有提供,我们将从模型中检测表名

如果您想要丢弃所有之前的更改和迁移并从头开始,可以使用以下命令

php artisan mapper:regenerate

调用它后,我们将删除所有迁移文件,所有日志,并从零开始。

在任何时候,如果您想要回滚最后一个生成过程,可以使用以下命令

php artisan mapper:rollback

支持的列类型

  • Boolean()
  • Date()
  • DateTme()
  • Time()
  • TinyInteger()
  • SmallInteger()
  • Integer()
  • MediumInteger()
  • BigInteger()
  • Decimal()
  • Double()
  • Float_()
  • Enum()
  • Id()
  • String_()
  • TinyText()
  • SmallText()
  • MediumText()
  • Text()
  • LongText()

这些类型中的每一种都有特定的参数,表示它可以处理的操作。

关系

此包还可以处理模型之间的关系。我们可能感兴趣的关系是 多对一多对多 关系,因为它们对模型本身有直接影响

假设我们有一个以下模型

#[Table(
    columns: [
        new Id(),
        new String_('name', length:255, default: "admin"),
        new BigInteger('category_id',unsigned: true,index: true),
    ]
)]
class Product extends Model
{
    protected $fillable = [
        'name','category_id'
    ]; 
    
    #[ManyToOne(related: Category::class)]
    public function category(): HasMany
    {
        return $this->belongsTo(Category::class, 'category_id')   
    }
    
    #[ManyToMany(related: Product::class, table: 'product_related', foreignKey: 'source_id', localKey: 'id', targetForeignKey: 'target_id', targetLocalKey: 'id')]
    public function related_products(): BelongsToMany
    {
        return $this->belongsToMany(Product::class,'product_related', 'source_id', 'target_id');
    }
    
}

通过调用 php artisan mapper:generate,该包将为您生成两个表,我们将得到以下结果

database
    migrations
        2024_02_19_1708369156_create_products_table_m.php
        2024_02_19_1708369157_create_product_related_table_m.php

请注意,其他类型的关联对模型没有影响,因此没有处理它们的想法。

许可证

Laravel 迁移映射器包根据 MIT 许可证(MIT) 许可。

安全联系方式

要报告安全漏洞,请直接联系开发者的联系邮箱 此处