将 parent_id 存储在 laravel 中

Store parent_id in laravel

我是 Laravel 的新手,所以我很挣扎。我有一个运行良好的评论系统,但现在我还想为其添加一个回复系统。所以我决定这样做的方法是在评论 table 中添加一个 parent_id 列,然后检查评论是否有父评论。但我不知道在这种情况下,存储方法究竟应该如何工作。这是我为评论设置的数据库:

public function up()
{
    Schema::create('comments', function (Blueprint $table) {
        $table->id();
        $table->foreignId('post_id')->constrained()->cascadeOnDelete();
        $table->foreignId('user_id')->constrained()->cascadeOnDelete();
        $table->text('body');
        $table->timestamps();

        });
}

现在为回复栏设置:

public function up()
{
    Schema::table('comments', function (Blueprint $table) {
        $table->unsignedBigInteger('parent_id')->nullable();

        $table->foreign('parent_id')->references('id')->on('comments');
    });
}

型号:

class Comment extends Model{
    use HasFactory;

    protected $guarded = [];

    public function post()
    {
        return $this->belongsTo(Post::class);
    }

    public function author()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function replies() {
        return $this->hasMany('App\Comment', 'parent_id');
    }
}

控制器:

public function store(Post $post){

    request()->validate([
        'body' => 'required'
    ]);

    $post->comments()->create([
        'user_id' => request()->user()->id,
        'parent_id' => request()->get('id'),
        'body' => request('body')
    ]);

    return back();
}

我只是不知道如何才能在商店功能中获得 parent_id 所以我会很感激一些建议

应该是回复的评论id

像这样

$post->comments()->create([
    'user_id' => request()->user()->id,
    'parent_id' => request()->get('comment_id'),
    'body' => request('body')
]);

希望对您有所帮助

使用代码:

public function store(Post $post) {

    request()->validate([
        'body' => 'required'
    ]);

    $post->comments()->create([
        'user_id' => request()->user()->id,
        'parent_id' => request()->get('comment_id'),
        'body' => request('body')
    ]);

    return back();
}