Laravel Nova - Only load relationship with certain property in form dropdown

此生再无相见时 提交于 2019-12-19 19:55:08

问题


I have added a BelongsTo relationship field(relationship name: user) in my Nova app in resource named "Partner". So in the "create partner" form now I have a select element to choose a specific user.

The relationship I have written includes a condition:

$this->belongsTo('App\User')->where('role', 'partner');

In the select dropdown, instead of only showing users with role "partner", all users of the app are listing. How can I fix this issue?

User table : id, name, role
Partner table : id, user_id, name

Partner Model:

class Partner extends Model
{

  protected $fillable = [
    'name', 'email', 'user_id'
  ];

  public function User()
  {
      return $this->belongsTo('App\User')->where('role', 'partner');
  }

}

Nova Resource fields method for Partner:

public function fields(Request $request)
{
    return [
        Text::make('Name')->sortable(),
        ID::make()->sortable(),
        BelongsTo::make('User', 'user', 'App\Nova\User')->rules('required'),
        HasMany::make('Clients'),
    ];
}

回答1:


You need to add the relatableQuery for User under Partner Nova resource. No need the where condition in Partner model.

use Laravel\Nova\Http\Requests\NovaRequest;
...

public static function relatableUsers(NovaRequest $request, $query)
{
    return $query->where('role', 'partner');
}


来源:https://stackoverflow.com/questions/53331599/laravel-nova-only-load-relationship-with-certain-property-in-form-dropdown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!