【发布时间】:2014-03-07 01:07:32
【问题描述】:
我需要在一个雄辩的查询上附加一个自定义选择,但我发现整个事情有点难以理解。这涉及一个论坛系统,其中每个论坛对象需要知道注册了多少个主题关系和评论关系。这是我到目前为止所得到的:
在 Forum.php 中
public function getNumTopics () {
return Topic::where('forum_id', '=', $this->id)->count();
}
public function getNumComments () {
return Comment::wherein('topic_id', Topic::where('forum_id', '=', 1)->lists('id'));
}
控制器返回 json
public function getCategories () {
$categories = ForumCategory::with('forums')->get();
foreach ($categories as $cat) {
if ($cat->forums->count() > 0) {
foreach ($cat->forums as $forum) {
/* @var $forum Forum */
$forum->num_topics = $forum->getNumTopics();
$forum->num_posts = $forum->getNumComments();
}
}
}
return Response::json($categories, 200);
}
调用大约需要 1300 毫秒才能返回三个类别的 5 个论坛。我怀疑这是因为它执行了大约 16 个查询而不是一个。有没有办法将“num_topics”和“num_posts”作为属性附加到选择上,以便我只执行一个查询?
编辑
我基本上想要的是当我要求 Forum::all() 时,Eloquent 会产生这样的东西:
select f.*,
ifnull(count(t.id), 0) num_topics,
ifnull(count(c.id), 0) num_posts
from forums f left join topics t on t.forum_id = f.id
left join comments c on c.topic_id = t.id
group by f.id
【问题讨论】:
-
我要尝试优化的第一件事是运行两个查询的 getNumComments 函数。此外,您的 getNumtTopics 和 getNumComments 都运行基本相同的查询,
Topic::where('forum_id'... -
我添加了我认为我希望 Eloquent 为我生成的查询。