简体   繁体   English

Laravel 5.7-通过访问者过滤分页的查询生成器?

[英]Laravel 5.7 - Filter a paginated query builder by an accessor?

I have a query builder that returns paginated data: 我有一个查询构建器,它返回分页数据:

$builder = Example::latest();
        $examples = $builder->with([
                                'activity',
                                'followers',
                                'messages',
                                'assignedTeam',
                                'domain',
                                'history'])
                        ->paginate();

        return response()->json($examples);

The model has an accessor, isRelativeTo that is a boolean value. 该模型有一个访问器isRelativeTo ,它是一个布尔值。 I want to filter this by !isRelativeTo . 我想用!isRelativeTo过滤它。 I know I can't map over it or add a filter directly, as it's not a collection, so wondering what the correct way of doing something like this might? 我知道我无法映射它或直接添加过滤器,因为它不是集合,所以想知道这样做的正确方法是什么?

Here is my accessor logic: 这是我的访问器逻辑:

public function getIsRelativeAttribute($value)
{
    $user = auth('api')->user();

    return $this->assigned_user_id == $user->id || $this->reported_by == $user->id
        || $user->teams()->where('id', $this->assigned_team_id)->exists();
}

I ended up creating scopes in addition to the accessor. 我最终除了访问器之外还创建了作用域。 In case anyone is curious: 如果有人好奇:

/**
 * Scope the query relative to the authenticated user
 *
 * @param \Illuminate\Database\Eloquent\Builder $query
 * @param \App\User $user
 *
 * @return \Illuminate\Database\Eloquent\Builder
 */
public function scopeRelativeTo($query, User $user)
{
    $teamIDs = $user->teams->pluck('id');

    $query->where('assigned_user_id', $user->id)
        ->orWhere('reported_by', $user->id)
        ->orWhereIn('assigned_team_id', $teamIDs);
}

/**
 * Scope the query NOT relative to the authenticated user
 *
 * @param \Illuminate\Database\Eloquent\Builder $query
 * @param \App\User $user
 *
 * @return \Illuminate\Database\Eloquent\Builder
 */
public function scopeNotRelativeTo($query, User $user)
{
    $teamIDs = $user->teams->pluck('id');

    $query->where(function ($q) {
        $user = auth('api')->user();
        $q->whereNull('assigned_user_id')
          ->orWhere('assigned_user_id', '!=', $user->id);
    })
   ->where('reported_by', '!=', $user->id)
   ->whereNotIn('assigned_team_id', $teamIDs);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM