LaravelORM中with,where,has,wherehas的使用

LaravelORM中with,where,has,wherehas的使用

2023年7月20日发(作者:)

LaravelORM中with,where,has,wherehas的使⽤共同之处,这三个函数的参数,都是 model 中的 relationship function 的名字。1 对 NN 对 Nwith类似于 SQL 中的 left join。左侧数据会全部显⽰。with 是 eager loading,即预加载关系数据。has类似于 SQL 中的 inner join。当右侧有数据时才会显⽰。注意,has 跟 whereHas 并不返回关系数据。whereHasinner join 之后,可以补充查询条件whereHas 实际应⽤场景例如,backpack 中的 N 对 N 关系的过滤,使⽤ whereHas$this->crud->addFilter([ // select2_multiple filter 'name' => 'roles', 'type' => 'select2_multiple', 'label'=> '⾓⾊'], function() { // the options that show up in the select2 return Role::all()->pluck('name', 'id')->toArray();}, function($values) { // if the filter is active foreach (json_decode($values) as $key => $value) { $this->crud->query = $this->crud->query->whereHas('roles', function ($query) use ($value) { $query->where('role_id', $value); }); }});if(!request('roles')){ $this->crud->addClause('whereHas', 'roles');}$users = User::whereHas('posts', function($q){ $q->where('created_at', '>=', '2015-01-01 00:00:00');})->get();with 的实际应⽤但是 with 的条件查询,并没有启动过滤左侧连表的作⽤,只会使右侧连表显⽰为 null。 所以是典型的 left join。例如,下⾯语句,还是会显⽰所有的发帖,⽽不是 is_master 的发帖。$items = Post::with(["user" => function($q){ $q->where('is_master', 1);}])->where('category_id', $category_id) ->where('status', 1) ->orderBy('id', 'desc') ->offset($offset) ->limit($limit) ->get();所以,这种情况下,应该使⽤ whereHas.注意whereHas 跟 with 的语法不⼀致whereHas 和 has 并不返回关系数据,但是 with 是返回的。所以,当要返回关系数据时,两者要结合使⽤。$items = Post::whereHas("user", function($q){ $q->where('is_master', 1);})->with(['user' => function($q) { $q->where('is_master', 1);}])->where('status', 1) ->where('top', 0) ->orderBy('id', 'desc') ->offset($offset) ->limit($limit) ->get();

发布者:admin,转转请注明出处:http://www.yc00.com/web/1689825202a288948.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信