资源
Nested resources
概述
关联管理器和关联页提供给你简单的方式让你在关联内渲染关联记录的表格。
比如,在 CourseResource 中,你可能有一个从属于该 Course 的 lessons 的关联管理器和关联页面。你可以通过打开模态框对话框从表格中创建、编辑课程。
然而,在模态框中创建并编辑 lesson 可能过于复杂。你可能希望 lesson 有他们自己的资源,以便创建和编辑 lesson 是通过全页面实现。这便是嵌套资源。
创建嵌入资源
要创建嵌入资源,你可以使用 make:filament-resource 并带上 --nested 选项:
php artisan make:filament-resource Lesson --nested
要访问嵌入资源,你同时页需要关联管理器和关联页。用户可以在此看到关联记录并点击链接去“新建”和“编辑”页面。
要创建关联管理器或者关联页,你可以使用 make:filament-relation-manager 或 make:filament-page 命令:
php artisan make:filament-relation-manager CourseResource lessons title
php artisan make:filament-page ManageCourseLessons --resource=CourseResource --type=ManageRelatedRecords
创建关联管理器或页面时,Filament 会询问你是否希望将每个表格行链接到一个资源,而不是打开一个模态框。你应该回答 “yes”,并选择刚刚创建的嵌套资源。
生成关联管理器或页面后,它将有一个属性指向嵌套资源:
use App\Filament\Resources\Courses\Resources\Lessons\LessonResource;
protected static ?string $relatedResource = LessonResource::class;
嵌套资源类将有一个属性指向父资源:
use App\Filament\Resources\Courses\CourseResource;
protected static ?string $parentResource = CourseResource::class;
自定义关联名
关联管理器和页面会根据关联中的模型预测关联的名称,嵌套资源也会这样做。有时,你的关联可能不符合传统的关联命名约定,你需要告知 Filament 嵌套资源的正确关联名称。
要自定义关联称,首先从嵌套资源类中移除 $parentResource 属性。然后定义 getParentResourceRegistration() 方法:
use App\Filament\Resources\Courses\CourseResource;
use Filament\Resources\ParentResourceRegistration;
public static function getParentResourceRegistration(): ?ParentResourceRegistration
{
return CourseResource::asParent()
->relationship('lessons')
->inverseRelationship('course');
}
如果你想使用默认名称,可以省略对 relationship() 和 inverse Relationship() 的调用。
Registering a relation manager with the correct URL
When dealing with a nested resource that is listed by a relation manager, and the relation manager is amongst others on that page, you may notice that the URL to it is not correct when you redirect from the nested resource back to it. This is because each relation manager registered on a resource is assigned an integer, which is used to identify it in the URL when switching between multiple relation managers. For example, ?relation=0 might represent one relation manager in the URL, and ?relation=1 might represent another.
When redirecting from a nested resource back to a relation manager, Filament will assume that the relationship name is used to identify that relation manager in the URL. For example, if you have a nested LessonResource and a LessonsRelationManager, the relationship name is lessons, and should be used as the URL parameter key for that relation manager when it is registered:
public static function getRelations(): array
{
return [
'lessons' => LessonsRelationManager::class,
];
}
Edit on GitHubStill need help? Join our Discord community or open a GitHub discussion