我选择与经过身份验证的用户属于同一组织的所有广播,这与->whereHas()
完美配合,但如果我想添加一个过滤器,只显示broadcasts
is_published
true
。
public static function indexQuery(NovaRequest $request, $query)
{
if (Auth::user()->isAdmin()) {
return $query;
}else{
return $query->whereHas('organizations', function($q){
$q->where('organization_id', Auth::user()->organization_id);
});
}
}
楷模
public function organizations()
{
return $this->belongsToMany('App\Models\Organization');
}
public function broadcasts()
{
return $this->belongsToMany('App\Models\Broadcast');
}
您可以在Broadcast
模型中添加一个查询范围,该模型将只查询broadcasts
,其中is_published
是true
(这对于您需要发布广播的应用程序中的未来查询很有用):
Broadcast.php(或模型文件)
public scopePublished($query)
{
return $query->where('is_published', true);
}
然后在您的代码中,以及->published()
范围到您的查询:
public static function indexQuery(NovaRequest $request, $query)
{
if (Auth::user()->isAdmin()) {
return $query;
} else {
return $query->published()
->whereHas('organizations', function($q){
$q->where('organization_id', Auth::user()->organization_id);
});
}
}