向 whereHas 添加额外的查询

Adding extra queries to whereHas

我正在选择与经过身份验证的用户属于同一组织的所有广播,这与 ->whereHas() 完美配合,但是如果我想添加一个过滤器以仅显示 broadcasts is_publishedtrue.

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_publishedtrue(这对您的应用程序中的未来查询很有用您需要发布广播的地方):

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);
            });
    }
}