[英]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.所以,我只想选择至少有 1 条评论的用户,并对该查询的结果进行分页。 Is there any way to do this?
有没有办法做到这一点?
根据Laravel查询关系的Eloquent 文档(查找“查询关系存在”子标题),这应该有效:
User::has('comments')->paginate(20);
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;
}
Simply like this:就像这样:
User::has('comments')->with('comments')->get(); User::has('comments')->with('comments')->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.