我正在尝试找出发布,评论和回复到评论的模式,其中< strong>回复只是单一级别(没有回复回复)。
发表:
1) id 2) user_id 3) contents 4) privacy
注释:
1) id 2) user_id 3) post_id 4) content
回复:
1) id 2) user_id 3) comment_id 4) content
最小化查询并获得最佳结果的可能方法是什么。
答案 0 :(得分:1)
根据上面的当前数据库结构,以下是表之间的关系。
因此,您需要在相应的模型中提供以下代码。
class Post extends Eloquent
{
/**
* Get all comments assign to single post
* @return \Illuminate\Database\Eloquent\Collection
*/
public function comments()
{
return $this->hasMany('App\Comment','post_id');
}
}
class Comment extends Eloquent
{
/**
* Get all replies assign to single comment
* @return \Illuminate\Database\Eloquent\Collection
*/
public function replies()
{
return $this->hasMany('App\Reply','comment_id ');
}
}
现在你收到了DB的所有帖子:
$posts = Post::all();
if($posts->count() > 0) {
foreach($posts as $post) {
// single post information
$comments = $post->comments;
if($comments->count() > 0) {
foreach($comments as $comment) {
// single comment information
$replies = $comment->replies;
if($replies->count() > 0) {
foreach($replies as $reply) {
// single reply information
}
}
}
}
}
}
如果您要获取单个帖子:
$post = Post::find($postId);
if($post->count() > 0) {
$comments = $post->comments;
if($comments->count() > 0) {
foreach($comments as $comment) {
// single comment information
$replies = $comment->replies;
if($replies->count() > 0) {
foreach($replies as $reply) {
// single reply information
}
}
}
}
}