Laravel 多对多加载相关模型与计数
问题描述
我正在尝试链接 4 个表,并添加一个自定义字段,该字段是通过使用 laravel 计算一些相关表的 id 来计算的.我在 SQL 中有这个功能,可以满足我的要求,但我认为它可以提高效率:
I am trying to link 4 tables and also add a custom field calculated by counting the ids of some related tables using laravel. I have this in SQL which does what I want, but I think it can be made more efficient:
我尝试通过这样做使用 eloquent 来实现它:
I tried to implement it using eloquent by doing this:
但是 NumComments 值未显示在查询结果中.任何线索如何去做?
However the NumComments value is not showing up in the query results. Any clue how else to go about it?
推荐答案
你不能用 with
做到这一点,因为它执行单独的查询.
You can't do that using with
, because it executes separate query.
你需要的是简单的join
.只需将您必须的查询翻译为:
What you need is simple join
. Just translate the query you have to something like:
那么集合中的每个帖子都会有计数属性:
then each post in the collection will have count attribute:
<小时>
但是,您可以通过以下关系使其更容易:
虽然第一个解决方案在性能方面更好(除非您拥有大数据,否则可能不会被注意到)
However you can make it easier with relations like below:
Though first solution is better in terms of performance (might not be noticeable unless you have big data)
这将允许您这样做:
对于多对多关系:
更多类似的例子可以在这里找到 http://softonsofa.com/tweaking-eloquent-relations-how-to-get-hasmany-relation-count-efficiently/
More examples like this can be found here http://softonsofa.com/tweaking-eloquent-relations-how-to-get-hasmany-relation-count-efficiently/
这篇关于Laravel 多对多加载相关模型与计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!