Languages

Version

Theme

资源

嵌入资源

概述

关联管理器关联页提供给你简单的方式让你在关联内渲染关联记录的表格。

比如,在 CourseResource 中,你可能有一个从属于该 Course 的 lessons 的关联管理器和关联页面。你可以通过打开模态框对话框从表格中创建、编辑课程。

然而,在模态框中创建并编辑 lesson 可能过于复杂。你可能希望 lesson 有他们自己的资源,以便创建和编辑 lesson 是通过全页面实现。这便是嵌套资源。

创建嵌入资源

要创建嵌入资源,你可以使用 make:filament-resource 并带上 --nested 选项:

php artisan make:filament-resource Lesson --nested

要访问嵌入资源,你同时页需要关联管理器关联页。用户可以在此看到关联记录并点击链接去“新建”和“编辑”页面。

要创建关联管理器或者关联页,你可以使用 make:filament-relation-managermake:filament-page 命令:

php artisan make:filament-relation-manager CourseResource lessons title

php artisan make:filament-page ManageCourseLessons --resource=CourseResource --type=ManageRelatedRecords

创建关联管理器或页面时,Filament 会询问你是否希望将每个表格行链接到一个资源,而不是打开一个模态框。你应该回答“是”,并选择刚刚创建的嵌套资源。

生成关联管理器或页面后,它将有一个属性指向嵌套资源: When creating a relation manager or page, Filament will ask if you want each table row to link to a resource instead of opening a modal, to which you should answer “yes” and select the nested resource that you just created.

After generating the relation manager or page, it will have a property pointing to the nested resource:

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() 的调用。

Edit on GitHub

Still need help? Join our Discord community or open a GitHub discussion

Previous
管理关联