dongtu7567 2018-01-03 03:32
浏览 47
已采纳

使用数据透视表过滤查询

I just want to ask on how to filter my query with a pivot table. This is how my tables are

users(id,name)

companies(id,name)

users_companies(id,user_id,company_id)

I really want to know how can i filter my list using drop down with pivot table Then this is how it goes to my 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);
            });
        }

This is for my list.blade or where my dropdown is located

<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>

Thank you so much experts!!!

  • 写回答

2条回答 默认 最新

  • drtoaamk20278 2018-01-08 09:51
    关注

    You can get users by using whereHas method, here is the example

    $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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • dsh84723 2018-01-09 02:23
    关注

    This is what i tried and it worked

    $query = User::whereHas('benefits', function ($q) use($benefit) {
                $q->where('benefit_id','=', $benefit);
            });
    
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 有人能代写linux应用吗?有偿,酬金可商量,具体要求联系我
  • ¥15 神经网络建立应力预测模型
  • ¥20 反编译一款APP手游,解密出lua脚本。
  • ¥15 改一下,代码,让代码符合要求
  • ¥15 报错问题,只有两个错误,如图片所示,i多次初始化
  • ¥15 matlab runtime 如何收费
  • ¥15 Tpad api账户 api口令
  • ¥30 ppt进度条制作,vba语言
  • ¥15 生信simpleaffy包下载
  • ¥15 在二层网络中,掩码存在包含关系即可通信