【问题标题】:Using with and withCount together in laravel eloquent在 laravel eloquent 中一起使用 with 和 withCount
【发布时间】:2017-01-31 12:33:07
【问题描述】:

withCount 是 laravel 的一种新方法,用于返回关系的计数。我正在尝试将 with 和 withCount 一起使用。例如:

Article::with('Comments')->withCount('Comments')->paginate();

我面临的问题是,结果见例如:

comments_count = 10
comments = []

它返回 cmets 数组 null。我不知道是否有可能得到两个结果。在不同网站上的一些文章中,我看到 withCount 仍然有一些限制。但不确定我正在尝试做的事情是否可行。

请帮助我了解这个问题。

谢谢,

【问题讨论】:

  • 是的。有可能得到这两个结果。你的代码可以做到这一点。你能显示那个查询的结果吗?
  • 如果我只使用 "WITH" 它返回: cmets:[{id:1, cmets:"---"},{id:2, cmets:"-----"} ],如果我使用在线 withCount,它会返回:cmets_count:2.... 如果我同时使用它会返回:cmets:[], cmets_count:2

标签: php laravel laravel-5 eloquent with-statement


【解决方案1】:

不需要写。

Article::withCount('Comments')->paginate();

【讨论】:

  • 感谢您的回复。但不幸的是,这对我不起作用。我试过了,但它只返回没有 cmets 的“cmets_count”。我也需要 cmets 数组。
  • 这不会加载关系,OP的代码是正确的。
猜你喜欢
  • 2018-07-11
  • 1970-01-01
  • 1970-01-01
  • 2022-12-26
  • 2019-08-06
  • 2022-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多