問題描述
幾天前,我看到一個網站,用戶可以在其中評論帖子.其他用戶可以回復.并且重播可以有像下面的示例截圖一樣的回復..
Few days ago, I saw a website where users can comment on a post. Other users can reply on that. and a replay can have replies like the example screenshot below..
所以我想試一試,但不知何故無法弄清楚.這是我的數據庫設置
So I thought to give it a try but somehow couldnt figure it out. here is my database set up
Schema::create('comments', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id');
$table->unsignedInteger('post_id');
$table->unsignedInteger('reply_id')->default(0);
$table->text('body');
$table->timestamps();
});
模型中的關系
class Comment extends Model
{
protected $fillable = [
'user_id',
'post_id',
'reply_id',
'body'
];
public function user()
{
return $this->belongsTo(User::class);
}
public function post()
{
return $this->belongsTo(Post::class);
}
public function replies()
{
return $this->hasMany(Comment::class,'reply_id','id');
}
在控制器中
$comments = Comment::with('replies')->where('reply_id','=',0)->get(['id','reply_id','body']);
return response($comments);
這完美地返回了評論和回復.但是如果有reply的回復,就不會顯示了.我怎樣才能做到這一點?需要建議.
this perfectly returns the comment and replies. But if there is a reply of reply, it doesnt show up. How can I do that? Need suggestion.
推薦答案
將 reply_id
與 nullable()
parent_id
交換.所以基本上你想知道評論是否有父級.
Swap reply_id
with a nullable()
parent_id
. So basically you want to know if a comment has a parent.
然后在Comment
模型中,添加一個self關系來獲取所有parent_id
匹配的評論.
Then in Comment
model, add a self relationship to take all comments whose parent_id
match.
public function replies() {
return $this->hasMany('AppComment', 'parent_id');
}
在您的視圖中,您可以為每個評論及其回復嵌套循環
In your view you can have nested loops for each comments and its replies
@foreach($comments as $comment)
{{ $comment->content }}
@if ( $comment->replies )
@foreach($comment->replies as $rep1)
{{ $rep1->content }}
...
@endforeach
@endif
@endforeach
這篇關于laravel eloquent 嵌套評論和回復的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!