Laravel的嵌套评论

Bra*_*don 2 php mysql laravel laravel-4

我目前正在尝试复制类似于论坛的内容,但我对如何创建嵌套注释感到困惑.我理解,对于常规回复,我可以创建一个回复表,并为每个与线程ID匹配的注释运行一个循环.但我不知道如何为嵌套回复轻松做到这一点.

有人可以给我一些建议或指出我正确的方向吗?谢谢.

这是我的帖子表的结构:

phpMyAdmin http://bitdrops.co/drops/J5v.png的屏幕截图

who*_*boy 8

您想要研究多态关系来解决这个问题.您希望能够对帖子和评论发表评论.

我所做的是设置一个可评论的特性,并让我想添加注释的模型使用它.这样,如果您想要评论另一个模型,您只需将该特征添加到该模型即可.

Laracasts是laravel的一个很好的资源,并且对特性有很好的教训.

还有一点比这更多,但希望它会让你开始.

您可以像这样设置数据库结构.

用户表

  `id` int(10),
  `name` varchar(255),
  `username` varchar(255)
Run Code Online (Sandbox Code Playgroud)

评论表

  `id` int(10),
  `user_id` int(10),
  `body` text,
  `commentable_id` int(10),
  `commentable_type` varchar(255)
Run Code Online (Sandbox Code Playgroud)

帖子表

  `id` int(10),
  `user_id` int(10),
  `body` text
Run Code Online (Sandbox Code Playgroud)

你的模特是这样的.

评论模型

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model {

    use CommentableTrait;

    /**
     * Get all of the owning commentable models.
     */
    public function commentable()
    {
        return $this->morphTo();
    }

    public function user()
    {
        return $this->belongsTo('App\User');
    }
}
Run Code Online (Sandbox Code Playgroud)

发布模型

<?php namespace App;

use CommentableTrait;
use Illuminate\Database\Eloquent\Model;

class Post extends Model {

    use CommentableTrait;

}
Run Code Online (Sandbox Code Playgroud)

当然你需要这个特质.

特征

<?php namespace App;

use Comment;

trait CommentableTrait {

    /**
     * List of users who have favorited this item
     * @return \Illuminate\Database\Eloquent\Relations\MorphToMany
     */
    public function comments()
    {
        return $this->morphMany('App\Comments\Comment', 'commentable')->latest();
    }

    /**
     * @return \Illuminate\Http\RedirectResponse
     */
    public function addComment($body, $user_id)
    {

        $comment = new Comment();
        $comment->body = $body;
        $comment->user_id = $user_id;

        $this->comments()->save($comment);

        return $comment;
    }

}
Run Code Online (Sandbox Code Playgroud)