acolorstory / nova-polymorphic-field
一个Laravel Nova字段容器,允许依赖于其他字段的值
1.0.6
2018-11-08 12:03 UTC
Requires
- php: >=7.1.0
This package is not auto-updated.
Last update: 2024-09-21 01:55:09 UTC
README
描述
一个Laravel Nova字段,允许你创建一个多态资源集合。
根据你选择的多态类型
- 不同的字段将在资源表单/详情页上填充。
- 记录将在相应的表中自动创建/更新。
演示
安装
该包可以通过Composer安装。
composer require michielkempen/nova-polymorphic-field
使用方法
- 将
morphs
字段添加到你的基础模型的迁移文件中。 - 将
MichielKempen\NovaPolymorphicField\HasPolymorphicFields
特性添加到你的Nova资源中。 - 将
MichielKempen\NovaPolymorphicField\PolymorphicField
添加到你的Nova资源fields
方法中。 - 通过在
PolymorphicField
上调用type($name, $modelClass)
方法来指定不同的多态类型。$name
参数是你为多态类型分配的可读名称。$modelClass
参数是多态模型的类。
示例
迁移
Schema::create('news_posts', function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->morphs('type'); // !! $table->timestamps(); }); Schema::create('videos', function (Blueprint $table) { $table->increments('id'); $table->string('url'); }); Schema::create('articles', function (Blueprint $table) { $table->increments('id'); $table->string('image'); $table->text('text'); });
资源
class NewsPost extends Resource { use HasPolymorphicFields; public function fields(Request $request) { return [ Text::make('Title'), PolymorphicField::make('Type') ->type('Video', \App\Video::class, [ Text::make('Url'), ]) ->type('Article', \App\Article::class, [ Image::make('Image'), Textarea::make('Text'), ]), ]; } }
在更新资源时,你可以选择隐藏类型选择。如果你不希望用户在创建多态关系后更改类型,这可能很有用。
class NewsPost extends Resource { use HasPolymorphicFields; public function fields(Request $request) { return [ ... PolymorphicField::make('Type') ->type('Video', \App\Video::class, [ Text::make('Url'), ]) ->type('Article', \App\Article::class, [ Image::make('Image'), Textarea::make('Text'), ]) ->hideTypeWhenUpdating(), ... ];
morphMap
默认情况下,相关模型的全限定类名将被存储为基础模型中的类型字段。但是,你可能希望将数据库与应用程序的内部结构解耦。在这种情况下,你可以定义一个“多态映射”关系,以指导Eloquent使用每个模型的自定义名称而不是类名。
use Illuminate\Database\Eloquent\Relations\Relation; Relation::morphMap([ 'article' => \App\Article::class, 'video' => \App\Video::class, ]);
你可以在AppServiceProvider
的boot
函数中注册morphMap
。
许可证
MIT许可证(MIT)。请参阅许可证文件获取更多信息。