使用 pivot table 过滤查询

Filtering query with pivot table

我只想问一下如何使用数据透视表过滤我的查询 table。我的table就是这样

用户(id,name)

公司(id,name)

users_companies(id,user_id,company_id)

我真的很想知道如何使用带有枢轴的下拉列表来过滤我的列表 table 然后这就是我的 EloquentUser

   public function paginate($perPage, $search = null, $status = null, $emp_status = null, $level = null, $age = null, $gender = null, $civil_status = null, $role_id = null, $birthmonth = null, $company = null)
    {
    $query = User::query();

    if($company && $company != "" && $company != "All" ) {
            $query->where(function ($q) use ($company) {
                $q->where('id', '=', $company);
            });
        }

这是我的 list.blade 或者我的下拉菜单所在的位置

<div class="form-group-sm"> 
                <select class="form-control form-control-sm" id="company" name="company">
                    <option selected  disabled>Company</option>
                    @foreach ($companies as $company)
                        @if (($company->id)=="1")
                        <option>All</option>
                        @else
                        <option value="{{ $company->id }}">{{ $company->name }}</option>
                        @endif
                    @endforeach
                </select>
            </div>

非常感谢各位专家!!!

你可以通过whereHas方法获取用户,这里是例子

$selected_company_id = $company; //this is form input, company which you selected

$users = User::whereHas('companies', function ($query) use($selected_company_id) {
    $query->where('company_id', $selected_company_id);
})->get();

这是我尝试过的并且有效

$query = User::whereHas('benefits', function ($q) use($benefit) {
            $q->where('benefit_id','=', $benefit);
        });