laravel当前表的外键

时间:2016-04-01 15:28:40

标签: php laravel eloquent

我有以下表格结构,允许用户提交评论或回复评论:

Schema::create('comments', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned()->nullable();
            $table->integer('model_id')->unsigned();
            $table->integer('parent_comment_id')->unsigned();
            $table->text('comment');
            $table->timestamps();

            $table->foreign('user_id')->references('id')->on('users')->onDelete('set null');
            $table->foreign('model_id')->references('id')->on('models')->onDelete('cascade');
            $table->foreign('parent_comment_id')->references('id')->on('comments')->onDelete('cascade');

        });

我有一个外键parent_comment_id,它指向comments表。这是为了表明评论(仍然是评论对象)属于父评论。

如何在模型中为评论表(/App/Comment.php)定义这种关系?

2 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情(在App\Comment模型中):

public function replies()
{
    return $this->childComments()->with('replies');
}

public function childComments()
{
    return $this->hasMany(Comment::class, 'parent_comment_id', 'id');
}

因此,您可以使用Comment::with('replies')递归加载所有相关回复。您可能会因为用于关系的两个函数而感到困惑,因为一个回复可能包含它自己的回复,因此您需要一个恢复性关系。因此,replies()将使用自己的回复加载所有回复。您也可以查看几年前我为Laravel - 4撰写的this post of mine,但这个想法是一样的。

// Another example could be something like this
$post = Post::with('comments.replies')->find(1); // Get Post with all comments with replies

注意:在这种情况下,Post模型必须包含comments()(hasMany)关系方法。

答案 1 :(得分:0)

您可以这样做:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    public function parentComment()
    {
        return $this->hasOne('App\Comment');
    }
}

您可以在this文档页面中查看更多信息。

相关问题