使用Eloquent时如何使用':: whereHas()'作为':: with()'查询的约束?

时间:2016-01-12 08:50:15

标签: laravel eloquent

我有一个问题:

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

它会返回所有包含评论名称为'asd'的帖子以及这些帖子的所有评论。我可以在“with”方法的':: whereHas'中使用上述约束,因此它不会返回所有注释,只会返回符合要求的注释吗?或者我是否必须复制查询?

1 个答案:

答案 0 :(得分:4)

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

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

或者,你可以在这篇文章中发表Laravel - is there a way to combine whereHas and with