最好的帖子,评论和回复架构

时间:2017-09-11 04:49:35

标签: mysql database laravel

我正在尝试找出发布评论回复评论的模式,其中< 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

最小化查询并获得最佳结果的可能方法是什么。

1 个答案:

答案 0 :(得分:1)

根据上面的当前数据库结构,以下是表之间的关系。

  • 帖子&amp; comments = OneToMany
  • 评论&amp;回复= OneToMany

enter image description here

因此,您需要在相应的模型中提供以下代码。

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 
                }
             }
        }
    }
}