我正在论坛上工作。我在Laravel和Eloquent中有以下模型结构:
Category hasMany Threads
Thread hasMany Posts
Thread hasManyThrough Reply, Post
Post hasMany Replies
我可以使用以下内容列出针对帖子的最新5条回复:
$recentReplies = $post->replies()->orderBy('created_at', 'desc')->take(5)->get();
我甚至可以使用hasManyThrough关系列出针对某个主题的最新5个回复:
$recentReplies = $thread->replies()->orderBy('created_at', 'desc')->take(5)->get();
我的问题是如何列出针对某个类别的最新5条回复?
以下不起作用:
$recentReplies = $category->threads()->replies()->orderBy('created_at', 'desc')->take(5)->get();
我也试过以下但失败了:
$recentReplies = $category->threads->replies()->orderBy('created_at', 'desc')->take(5)->get();
我有以下样本模型结构:
class Category extends Eloquent {
public function threads()
{
return $this->hasMany('Thread');
}
}
class Thread extends Eloquent {
public function posts()
{
return $this->hasMany('Post');
}
public function replies()
{
return $this->hasManyThrough('Reply', 'Post');
}
}
class Post extends Eloquent {
public function replies()
{
return $this->hasMany('Reply');
}
}
class Reply extends Eloquent {
// NOTE: belongsTo method exists in all models
}
提前感谢您的所有时间和精力?
问候
艾哈迈德汗答案 0 :(得分:1)
使用这个技巧:
$recentReplies = null;
// let's find 5 replies for category with $categoryId
Category::with(['threads.replies' => function ($q) use (&$recentReplies) {
$recentReplies = $q->latest()->take(5)->get();
}])->find($categoryId);