在选择字段中返回表的所有行laravel Nova

时间:2020-06-29 21:45:46

标签: php laravel laravel-nova

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

我当前用于Select的项目

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

            ])
                ->displayUsingLabels(),

这是我的类别表的标题:

Categories table

1 个答案:

答案 0 :(得分:2)

我了解您在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中,您不是将“孩子”及其父对象之间的关系表示为“选择”字段,而是表示为BelongsTo,例如:

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

但是您可以使用“选择”字段来预先加载一个类别数组,以便您可以仅过滤当前类别onOns()。

您可以这样操作:

 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(),
       
        ];


}