【问题标题】:Best possible schema of post, comments and replies帖子、评论和回复的最佳可能模式
【发布时间】:2017-09-11 04:49:34
【问题描述】:

我正在尝试找出 postcmetsrepliescmets 的架构,其中 回复 只是单级(不回复回复)。
发帖

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

有什么方法可以最小化查询并获得最佳结果。

【问题讨论】:

  • 你有能力删除/编辑他的评论或回复评论吗?
  • 所有 CRUDE 操作都可以在帖子、评论和回复中进行
  • 那么你当前的数据库结构很好,因为 Laravel 提供了 Eloquent ORM,你可以使用它的关系方法来获取信息。
  • 我可以得到这个的关系代码吗?

标签: mysql database laravel


【解决方案1】:

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

  • 帖子和 cmets = OneToMany
  • 评论和回复 = OneToMany

You can read more about relationships in Laravel

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

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

【讨论】:

  • 当帖子和评论数量变多时,这会占用我的内存,我该如何分块?
  • 您可以显示有限制的 cmets,并提供加载更多按钮来加载相应的 cmets 和回复。
猜你喜欢
  • 2016-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多