2

I am developing a Web Application using Laravel. I am using Laravel Nova for building the admin panel. But I am having an issue with BelongsToMany field.

I have the database schema as follow

Area

Station - has area_id because an area has many stations

manager - area_id because each user belongs to an area

Area_station - station_id and manager_id (many to many)

So in the Station nova resource, I added a field like this.

BelongsToMany::make('Managers', 'managers', Manager::class),

Therefore, when I go to the Station details page from the Nova admin panel and select "Attach manager", in the dropdown of the next page (page to attach a manager to the department), I can see all the available managers in the database.

But instead of displaying all the available managers in the drop down, I like to filter the managers/users which belongs to the same area as the selected Station. I mean when I attached a manager to the Station, I have to select a station. Is it possible to filter or to achieve what I want in Nova?

4

1 回答 1

5

覆盖relatableQuery函数,它将确定模型的哪些实例可以附加到Managernova 资源下的其他资源。

方法一

public static function relatableQuery(NovaRequest $request, $query)
{
    // In case manager is get attached to another resource except Station. 
    if ($request->resource() == 'App\Nova\Station') { 
        $station = $request->findResourceOrFail();
        return $query->where('area_id', $station->area_id);
    }

    return parent::relatableQuery($request, $query);
}

更新

方法 2 - 刚刚学到了一些新东西。

Station您可以为Nova 资源下的关系添加相关查询。在这种情况下,无需检查资源。

public static function relatableManagers(NovaRequest $request, $query)
{
    $station = $request->findResourceOrFail();
    return $query->where('area_id', $station->area_id);
}

我认为方法2更好。

于 2018-11-09T05:51:37.687 回答