【问题标题】:Lumen/Laravel Eloquent - filter by attribute in pivot tableLumen/Laravel Eloquent - 按数据透视表中的属性过滤
【发布时间】:2021-01-09 10:29:45
【问题描述】:

我有三个表,userstalentsuser_talent 作为数据透视表,我正在尝试根据用户的才能过滤用户。关系是用户可以拥有多个人才,人才可以分配给多个用户。

关系:

public function talents() {
    return $this->belongsToMany('App\Models\Talent');
}

public function users() {
    return $this->belongsToMany('App\Models\User');
}

这运作良好。现在我正在尝试根据人才 ID 过滤用户,但我没有这样做。

与: Talent 模型不使用 $with,而 User 使用:

protected $with = [
    'talents'
];

过滤器(请注意我删除了其他过滤器和分页器):

public function getAllModelsWithFilters(Request $request) {
    $model = User::query();
        $sortColumn = 'full_name';
        $sortDir = 'orderBy';

    if ($request->has('talents')) {
        $ids = [];
        $array = explode(',', $request->query('talents')); // provided as string: 1,2,3,6
        foreach($array as $arr) {
            $res = (int) $arr;
            if (!empty($res)) {
                $ids[] = $res;
            }
        }

        if (!empty($ids)) {
            $model->with([
                'talents' => function ($q) use ($ids) {
                    $q->whereIn('talents.id', $ids);
                }
            ]);
        }
    }

    return CustomResponse::success([
        'data' => $model->{$sortDir}($sortColumn)->get()
    ]);
}

结果

结果是我找回了所有用户,即使是那些没有分配才能的用户。

预期结果

根据才能过滤的用户集合。

使用 Lumen v7.1.3

【问题讨论】:

    标签: eloquent lumen


    【解决方案1】:

    在这里得到答案:laravel belongsToMany Filter

    上面的代码改成:

    if ($request->has('talents')) {
        $ids = [];
        $array = explode(',', $request->query('talents')); // provided as string: 1,2,3,6
        foreach($array as $arr) {
            $res = (int) $arr;
            if (!empty($res)) {
                $ids[] = $res;
            }
        }
        if (!empty($ids)) {
            $model->whereHas('talents', function($q) use ($ids) {
                $q->whereIn('talents.id', $ids);
            });
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-17
      • 1970-01-01
      • 2017-09-30
      • 2018-11-24
      • 1970-01-01
      • 2013-09-03
      • 2017-02-28
      • 1970-01-01
      相关资源
      最近更新 更多