问题
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?
回答1:
According to Laravel's Eloquent documentation for querying relations (look for the "Querying Relationship Existence" subheading), this should work:
User::has('comments')->paginate(20);
回答2:
Flip your thinking upside down and I think that you can do it.
$userIds = Comment::distinct()->select('user_id')->groupBy('user_id')->get();
You may not need the groupBy()
but that should get you started towards a way to do it.
Then you should be able to iterate through each like so:
foreach($userIds as $id) {
$user = $id->user; //$id is technically a Comment instance so you can
// call the methods on that model
echo $user->name;
}
来源:https://stackoverflow.com/questions/31598949/laravel-eloquent-select-only-rows-where-the-relation-exists