使用雄辩时,如何使用':: whereHas()'作为':: with()'查询的约束? [英] How to use '::whereHas()' as a constraint for '::with()' query when using Eloquent?

查看:72
本文介绍了使用雄辩时,如何使用':: whereHas()'作为':: with()'查询的约束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个查询:

Posts::whereHas('comments', function($query){
          $query->where('name', 'like', 'asd');
      })->with('comments')->get();

它将返回所有带有 asd之类名称的评论以及所有这些评论。我可以在 :: whereHas中为 with方法使用上述约束,以便它不返回所有注释,而仅返回符合要求的注释?还是我必须重复查询?

It returns all posts that have comments which have name like 'asd' with all comments of these posts. Can I use the above constraint in '::whereHas' for the 'with' method, so it would not return all comments, but only those that match the requirements? Or do I have to duplicate the query?

推荐答案

您可以创建类似这样的查询,几乎没有重复:)

You can create query something like this, almost without duplicate :)

$callback = function($query) {
     $query->where('name', 'like', 'asd');
}
Posts::whereHas('comments', $callback)->with(['comments' => $callback])->get();

或者,您可以像这篇文章中那样 Laravel-有一种方法可以将whereHas和与

Or, you can make like in this post Laravel - is there a way to combine whereHas and with

这篇关于使用雄辩时,如何使用':: whereHas()'作为':: with()'查询的约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆