Laravel nova overriding/setting Fields 或 Has Through 关系的自定义值

Laravel nova overriding/setting custom value for the Fields or Has Through relationship

我正在使用 Laravel 开发 Web 应用程序。对于管理面板,我使用的是 Laravel Nova。我现在要做的是我需要使用来自 table 的数据,它与另一个 table 有关系。明确地说,请参阅下面我的数据库结构。

items
=====
id
name
price
sub_category_id

sub_categories
==============
id
name
parent_category_id

parent_categories
=================
id
name

我想在 Nova 中实现的是,我想在项目 index/list 页面上显示项目的父类别名称。第一件事是我不想在模型中创建这样的自定义属性

protected $appends = [
        'parent_category_name'
    ];

function getParentCategoryNameAttribute()
{
    //code here
}

因此,我想到了两种解决方案。第一个解决方案是使用 HasThrough 关系。但是我在 Nova 找不到它。所以,我不能使用它。第二种解决方案是覆盖渲染时的字段值。像这样。

Text::make("fieldname")->fillUsing(function($request, $model, $attribute, $requestAttribute) {
                //$model->sub_category->parent_category - then I can return a value
                return "Parent category name";
            })->onlyOnIndex()

但是上面的代码不起作用。那么,在 Nova 中处理 has-through 关系的最佳方法是什么?

假设您已正确定义关系 sub_categoryparent_category

定义 Item 模型中的关系如下

public function parent_category()
{
    return $this->sub_category->parent_category();
}

然后在 Item 资源中使用它,如下所示。

BelongsTo::make('Parent Category')
    ->hideWhenCreating()
    ->hideWhenUpdating(),