rsubr/nova-json-schema-field

Laravel Nova 字段用于 JSON Schema。

v1.0.0-RC1 2021-06-19 04:49 UTC

This package is not auto-updated.

Last update: 2024-09-22 18:44:01 UTC


README

Packagist

Laravel Nova 字段,用于显示 JSON schema 数据。受 nsavinov/nova-json-schema-field 启发。

安装

您可以通过 composer 将包安装到使用 Nova 的 Laravel 应用中

composer require rsubr/nova-json-schema-field

用法

在 Laravel 模型中

    use Illuminate\Database\Eloquent\Casts\AsCollection;

    protected $casts = [
        'details' => AsCollection::class,
    ];

    // NovaJsonSchemaField does not like empty JSON, so use an empty placeholder
    protected $attributes = [
        'details' => '{"_": ""}',
    ];

使用静态 Schema

在 Nova 资源中

use Rsubr\NovaJsonSchemaField\NovaJsonSchemaField;

public function fields(Request $request)
{
    return [
        // ...
        NovaJsonSchemaField::make('Details')
            ->jsonSchema($this->loadSchema())
            ->rules('json'),
    ];
}

private function loadSchema(): array
{
    $schema = <<<SCHEMA
        {
            "type": "object",
            "required": [
                "event_name",
                "level",
                "start_date",
                "duration"
            ],
            "properties": {
                "event_name": {
                    "description": "Event Name"
                },
                "level": {
                    "type": "array",
                    "items": {
                        "enum": [
                            "State Level",
                            "National",
                            "International"
                        ]
                    },
                    "description": "Event level"
                },
                "start_date": {
                    "type": "string",
                    "format": "date",
                    "description": "Start Date"
                },
                "duration": {
                    "type": "number",
                    "description": "Duration in Days"
                }
            }
        }

    SCHEMA;
    return json_encode($schema, true);
}

使用动态 Schema

可以从相关的模型或 API 中动态加载 schema。

例如,要从 EventType 模型加载 JSON schema,首先在模型上创建一个属性,并在 Nova 资源中调用。

在 Laravel 模型中

    public function getJsonSchemaAttribute() {
        return $this->event_type->json_schema;
    }

event_type 模型应与持有 JSON 数据的模型有 HasMany 关系。

在 Nova 资源中

    protected function loadSchema($request)
    {
        // NovaJsonSchemaField does not like empty JSON, so use an empty placeholder
        $schema = $request->findModelQuery()->first()->json_schema ?? array();

        return $schema;
    }

注意

  1. 对于 PostgreSQL,使用 JSON 列存储 JSON Schema 以保留字段顺序,不要为 schema 使用 JSONB。JSON 数据值可以存储在 JSONJSONB 中。