向whereHas添加额外查询

问题描述 投票:0回答:1

我选择与经过身份验证的用户属于同一组织的所有广播,这与->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');
}
laravel-5 laravel-nova
1个回答
2
投票

您可以在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);
            });
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.