Laravel Eloquent, select only rows where the relation exists

妖精的绣舞 提交于 2019-12-05 03:02:29

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

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.

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!