【问题标题】:Laravel nova overriding/setting custom value for the Fields or Has Through relationshipLaravel nova 覆盖/设置 Fields 或 Has Through 关系的自定义值
【发布时间】:2019-04-06 18:23:56
【问题描述】:

我正在使用 Laravel 开发一个 Web 应用程序。对于管理面板,我使用的是 Laravel Nova。我现在要做的是我需要使用与另一个表有关系的表中的数据。为了清楚起见,请参阅下面的我的数据库结构。

items
=====
id
name
price
sub_category_id

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

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

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

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 中处理直通关系的最佳方法是什么?

【问题讨论】:

    标签: laravel laravel-nova


    【解决方案1】:

    假设你已经正确定义了sub_category & parent_category 的关系。

    在Item模型中定义如下关系

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

    然后在Item资源中使用如下。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-24
      • 2019-02-22
      • 1970-01-01
      • 2020-05-03
      • 2019-05-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多