Laravel Eloquent, select only rows where the relation exists

亡梦爱人 提交于 2019-12-10 03:09:01

问题


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

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