How to use '::whereHas()' as a constraint

2020-04-21 04:27发布

问题:

I have a query:

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

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?

回答1:

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();

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