Laravel Eloquent,只选择关系存在的行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31598949/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel Eloquent, select only rows where the relation exists
提问by Kenyon
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 条评论的用户,并对该查询的结果进行分页。有没有办法做到这一点?
回答by Don't Panic
According to Laravel's Eloquent documentationfor querying relations (look for the "Querying Relationship Existence" subheading), this should work:
根据Laravel查询关系的Eloquent 文档(查找“查询关系存在”子标题),这应该有效:
User::has('comments')->paginate(20);
回答by Kyle
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.
您可能不需要,groupBy()
但这应该会让您开始找到一种方法。
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;
}