dsyk33753 2018-10-19 17:50
浏览 80
已采纳

Laravel 5.7 - 由访问者过滤分页查询构建器?

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. I want to filter this by !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();
}
  • 写回答

1条回答 默认 最新

  • donglei1699 2018-10-19 20:08
    关注

    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);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题