andyabih/json-to-laravel-migrations

将JSON模式转换为Laravel迁移。

1.0.0 2021-03-21 21:26 UTC

This package is not auto-updated.

Last update: 2024-09-17 12:16:43 UTC


README

只需在项目的根目录中创建一个包含数据库模式的 .json 文件,然后运行 artisan 命令 json:migrate schema.json 以创建项目中的所有迁移。

注意:此包旨在用于启动您的Laravel项目,而不是用于已构建的项目。

安装

您可以通过运行以下 composer 命令安装此包:

composer require --dev andyabih/json-to-laravel-migrations

创建JSON模式

在项目根目录中创建一个 schema.json 文件,并使用以下模板:

{
    "posts": {
        "name"   : "string:50|index:50",
        "state"  : "enum:active,inactive|default:active",
        "text"   : "text",
        "slug"   : "string:50|unique",
        "active" : "boolean|default:false",
        "user_id": "foreign|nullable|constrained|onDelete"
    },

    "categories": {
        "name" : "string",
        "image": "string"
    },

    "subcategories": {
        "name"       : "string",
        "category_id": "foreign|constrained"
    }
}

JSON的主要键代表表名。请确保按顺序创建它们,以防某个表与其他表有关联。在这种情况下,postscategoriessubcategories 是我们的表。

接下来,为每个表定义您的列作为键(在这种情况下,为 namestatetext 等),并设置它们的属性。

属性

属性通过竖线 (|) 分隔,第一个属性始终是列类型。该包支持Laravel中的所有列类型。

可以使用冒号 (:) 后跟选项值提供附加选项(例如,字符串长度)。可以为多个选项提供值(例如,对于 float)。

迁移

使用以下命令运行上述操作:

php artisan json:migrate schema.json

上述模式将创建三个不同的迁移。posts 模式看起来如下:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string("name", 50)->index();
            $table->enum("state", ['active', 'inactive'])->default('active');
            $table->text("text");
            $table->string("slug", 50)->unique();
            $table->boolean("active")->default(false);
            $table->foreignId("user_id")->nullable(true)->constrained()->onDelete('cascade');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

未来计划

  • 创建关联表。
  • 创建模型(带关系)。
  • Backpack 集成。Backpack 是我最喜欢的管理面板,我很乐意看到与它们集成的某些内容,并自动创建 CRUD 控制器与字段。
  • 欢迎任何建议!无论您有什么想法,请告诉我。