3

I am developing a Web application using Laravel. For the admin panel, I am using Laravel Nova. What I am trying to do now is that I need to use data from the table which has relationship through another table. To be, clear, see my database structure below.

items
=====
id
name
price
sub_category_id

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

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

What I am trying to achieve inside the Nova is that I want to display the parent category name of the item on the item index/list page. The first thing is that I do not want to create custom attribute something like this in the model

protected $appends = [
        'parent_category_name'
    ];

function getParentCategoryNameAttribute()
{
    //code here
}

Therefore, there are two solutions I can think of. The first solution is using the HasThrough relationship. But I cannot find it in Nova. So, I cannot use it. The second solution is that overriding the field value on render. Something like this.

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()

But the above code is not working. So, what would be the best approach to handle the has-through relationship in Nova?

4

1 回答 1

1

Assuming you have defined the relationship sub_category & parent_category properly.

Define the relationship in Item model as below

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

Then use it in Item resource as below.

BelongsTo::make('Parent Category')
    ->hideWhenCreating()
    ->hideWhenUpdating(),
于 2018-11-12T07:37:10.503 回答