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

报告相同问题?

悬赏问题

  • ¥15 kubeadm部署k8s出错
  • ¥15 Abaqus打不开cae文件怎么办?
  • ¥20 双系统开机引导中windows系统消失问题?
  • ¥15 小程序准备上线,软件开发公司需要提供哪些资料给甲方
  • ¥15 关于生产日期批次退货退款,库存回退的问题
  • ¥15 手机应用的时间可以修改吗
  • ¥15 docker 运行OPEN-webui异常
  • ¥15 麒麟系统如何删除光盘刻录痕迹
  • ¥15 recipe通过gem协议传的是什么
  • ¥15 TS2307: Cannot find module 'cc'.