首页 > 解决方案 > 返回选择字段 laravel Nova 中的所有表行

问题描述

我想返回我的选择我的“类别”表的所有元素,除了当前行。我在互联网上没有找到任何关于此的信息,所以我来找你。

我当前选择的项目:

Select::make('Parent Category')
                ->options([

            ])
                ->displayUsingLabels(),

这是我的类别表的标题:

类别表

标签: phplaravellaravel-nova

解决方案


我了解您在 Category 模型与其自身之间存在自引用关系,例如

class Category extends Model
{

    public function parent()
    {
        return $this->belongsTo(Category::class, 'parent_id');
    }

    public function children()
    {
        return $this->hasMany(Category::class, 'parent_id');
    }
}

在 Nova 中,您通常不会将 Child 与其 Parent 之间的关系表示为 Select 字段,而是表示为 BelongsTo,例如:

    BelongsTo::make('Parent Category', 'parent', Category::class)->searchable()->nullable(),

但是您可以使用 Select 字段来预加载类别数组,以便您可以过滤掉当前类别 onlyOnForms()。

你可以这样做:

 public function fields(Request $request)
 {
     
        $fields = [
            
            // [ All your fields ]
            
            // We'll use a Select but onlyOnForms to show all categories but current category when in Forms
            Select::make('Parent', 'parent_id')->options(Category::where('id', '!=', request()->resourceId)->pluck('name', 'id'))->onlyOnForms(),

            // Use a BelongsTo to show the parent category when in Details page
            BelongsTo::make('Parent', 'parent', Category::class)->searchable()->nullable()->showOnDetail()->hideWhenCreating()->hideWhenUpdating(),
       
        ];


}

推荐阅读