【问题标题】:Adding extra queries to whereHas向 whereHas 添加额外的查询
【发布时间】:2019-03-28 10:13:43
【问题描述】:

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

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】:

    您可以将查询范围添加到您的 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);
                });
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多