dongxiqian2787 2014-11-04 16:17
浏览 274
已采纳

Laravel Eloquent“With”过滤器

Let's say I have the following setup. A User has many Coments. In my REST API I have an action /users where I display all the users and their comments.

I would do that like this:

return Response::json(User::with('comments')->get(), 200);

But now I only want to display a User in that list if it has at least one Comment. Something in the lines of:

return Response::json(User::with('comments')->whereCount('users.comments', '>', 0)->get(), 200);

But that obviously does not work. What is the correct way to do this in conjunction with the with method?

  • 写回答

1条回答 默认 最新

  • duandang9434 2014-11-04 16:20
    关注

    You can use in this case has to get only users that has at least one comment:

    return Response::json(User::with('comments')->has('comments')->get(), 200);
    

    Reference

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题