美文网首页
laravel中with和whereHas使用笔记!

laravel中with和whereHas使用笔记!

作者: DragonersLi | 来源:发表于2019-07-28 00:05 被阅读0次
移民国家列表查询,每个国家对应多个类别。每个类别下有多个国家,属于多对多关系。国家表和类别表通过中间表关联。
image.png
移民国家表模型定义多对多关联关系
    public function country_types(){
      #移民国家表模型: belongsToMany(移民类别模型,中间关系模型)
       return $this->belongsToMany(YmType::class,YmCountryType::class);
    }

移民国家列表控制器方法

查询没有条件筛选直接with就可以搞定,但是查询条件有移民类别ID,但是移民国家和移民类别是通过中间表关联起来的,移民国家表中并没有这个字段。使用with查询筛选失效。这时就需要使用whereHas来过滤with查询出来的数据了。此种写法虽优雅但感觉性能没有join高效易于理解。

        $region_id = $request->region_id ?? 0;
        $type_id = $request->type_id ?? 0;
        $where = [];
        $region_id && $where['region_id'] = $region_id;
 # \DB::connection()->enableQueryLog();  // 开启QueryLog
        $data = $this->ymCountry
            ->where($where)
            ->with(['country_types'=>function($query) use($type_id){
                $type_id && $query->where(['ym_type_id'=>$type_id])->select(['ym_type_id','ym_country_id','title']);
            }])
            ->whereHas('country_types', function ($query) use ($type_id) {
                $type_id && $query->where('ym_type_id', $type_id);
            })
            ->orderBy('sort','desc')
            ->paginate(10);
   #dlog('type',\DB::getQueryLog());
        return view('home.country.index', compact( 'data'))->with(['footer'=>$this->footer]);

总结:with中where条件不起作用,要在whereHas中设置

移民国家表ym_contries

image.png

移民类别表ym_types

image.png

移民国家表和类别表的多对多映射关系表ym_country_types

image.png

相关文章

网友评论

      本文标题:laravel中with和whereHas使用笔记!

      本文链接:https://www.haomeiwen.com/subject/yiiyrctx.html