Laravel Eloquent,只选择关系存在的行


Laravel Eloquent, select only rows where the relation exists

我试图从表中选择,但我只想选择具有现有关系的事物。

例如,如果我有用户和评论,用户有许多评论,我想做这样的事情:

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

因此,我只想选择至少有1条评论的用户,并对该查询的结果进行分页。有什么办法可以做到吗?

根据Laravel的Eloquent文档查询关系是否存在,您可以使用has()方法:

User::has('comments')->paginate(20);

把你的想法颠倒过来,我认为你能做到。

$userIds = Comment::distinct()->select('user_id')->groupBy('user_id')->get();

你可能不需要groupBy(),但这应该让你开始朝着一个方法去做。

那么你应该能够像这样遍历每一个:

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;
}

就像这样:

用户::("评论")→与("评论")→();