Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent, select only rows where the relation exists

I am trying to select from a table, but I only want to select things that have an existing relationship.

For example, if I have Users and Comments, and Users haveMany Comments, I want to do something like:

User::hasComments()->paginate(20);

So, I only want to select Users that have at least 1 Comment, and paginate the result of that query. Is there any way to do this?

like image 299
Kenyon Avatar asked Jul 23 '15 22:07

Kenyon


1 Answers

According to Laravel's Eloquent documentation for querying relations (look for the "Querying Relationship Existence" subheading), this should work:

User::has('comments')->paginate(20);
like image 120
Don't Panic Avatar answered Sep 21 '22 05:09

Don't Panic