通过聚合关系进行雄辩查询

时间:2014-09-22 09:54:46

标签: laravel eloquent

我想通过模型关系中的聚合值进行查询。 例如,我应该只获得帖子,其中包含两个日期之间的最后一条评论。

SELECT posts.*, MAX(comments.created_at) 
as max FROM posts 
JOIN comments ON (comments.post_id = posts.id)
GROUP BY posts.id HAVING max > '2014-01-01 00:00:00' AND max < '2014-02-01 00:00:00'

1 个答案:

答案 0 :(得分:2)

使用内置方法代替连接:

// Assuming you have relations setup
Post::whereHas('comments', function ($q) use ($from, $till) {
   $q->groupBy('post_id')
     ->havingRaw("max(created_at) between '{$from}' and '{$till}'");
})->get();

它会产生:

select * from `posts` where 
  (select count(*) from `comments` where `comments`.`post_id` = `posts`.`id` 
    group by `post_id`
    having max(created_at) between '2014-01-01' and '2014-02-01'
  ) >= 1 limit 1