我试图让我的用户(作者实际上,将有最多5-6个作者)与他们的最后一篇文章显示在主页的侧边栏中。由于它们将在主页中列出,我正在努力减少由于性能问题而导致的sql查询的数量。我试过了;
$users=User::with(array('posts'=>function($query){
$query->take(1);
}))->get();然而,它总共只有一个帖子,而不是每个用户都有一个帖子。而且我的sql知识也是有限的。
如何使用雄辩的ORM、查询生成器或原始sql查询来解决我的问题?
发布于 2013-04-20 23:31:44
一种解决方案是在User模型上定义一个hasOne关系,按posts的created_at列排序。
public function lastPost()
{
return $this->hasOne('Post')->orderBy('created_at', 'desc');
}那么你的查询就是这样的。
$users = User::with('lastPost')->get();要限制列,您可以在关系级别约束查询:
return $this->hasOne('Post')->select('id', 'user_id', 'title', 'created_at')->orderBy('created_at', 'desc');或者当您使用with方法时:
$users = User::with(['lastPost' => function($query)
{
$query->select('id', 'user_id', 'title', 'created_at');
})->get();注意,您还需要user_id和created_at列,因为它们是查询中的WHERE和ORDER BY子句所必需的。
发布于 2013-04-20 23:35:00
执行此操作的一般SQL方法是:
select p.*
from posts p join
(select p.authorid, max(created_at) as maxdate
from posts p
group by p.authorid
) psum
on p.authorid = psum.authorid and p.created_at = psum.maxdate这假设没有重复项。
根据您正在使用的数据库,肯定还有其他方法来编写此查询。该版本是标准SQL。
https://stackoverflow.com/questions/16121543
复制相似问题