Laravel Eloquent,仅选择存在关系的行 [英] Laravel Eloquent, select only rows where the relation exists

查看:72
本文介绍了Laravel Eloquent,仅选择存在关系的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从表中进行选择,但是我只想选择具有现有关系的事物.

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

因此,我只想选择具有至少1条注释的用户",并分页该查询的结果.有什么办法吗?

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?

推荐答案

根据

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

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

这篇关于Laravel Eloquent,仅选择存在关系的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆