首页 > 解决方案 > Lumen/Laravel Eloquent - 按数据透视表中的属性过滤

问题描述

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

关系:

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

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

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

With: 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()
    ]);
}

结果

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

预期成绩

根据人才筛选的用户集合。

使用流明 v7.1.3

标签: eloquentlumen

解决方案


在这里得到答案:laravel belongsToMany 过滤器

将上面的代码更改为:

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);
        });
    }
}

推荐阅读