几天前,我看到一个网站,用户可以在帖子上发表评论。其他用户可以回复此问题。并且重播可以有回复,如下面的示例屏幕截图..
所以我想试一试,但不知何故无法弄明白。 这是我的数据库设置
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);
这完美地回复了评论和回复。但如果有回复的回复,它就不会显示出来。我怎样才能做到这一点?需要建议。
答案 0 :(得分:8)
使用#include <fstream>
#include <zip.h>
#include "lib/zip.hpp"
int main () {
libzip::Archive archive("output.zip", ZIP_CREATE);
std::ofstream outfile ("myfile.txt");
outfile << "Hello World\n";
outfile.close();
archive.add(libzip::source::file("myfile.txt"), "myfile2.txt");
// delete archive; // throws an error...
// remove("myfile.txt");
// if left out, output.zip gets created otherwise nothing is created
return 0;
}
reply_id
交换nullable()
。所以基本上你想知道评论是否有父母。
然后在parent_id
模型中添加自我关系,以获取Comment
匹配的所有评论。
parent_id
在您的视图中,您可以为每个评论及其回复添加嵌套循环
public function replies() {
return $this->hasMany('App\Comment', 'parent_id');
}