2 回答

TA貢獻1863條經驗 獲得超2個贊
實際上,如果您只想“一級回答”,則只需兩張桌子。
第一個是“comment_answer”,包含評論和答案。評論和答案不需要額外的表格,因為每條評論都有一個答案,不是嗎?因此,我們可以將每個答案與其相關的問題保存在同一記錄中。像這樣遷移;
Schema::create('comment_answer', function (Blueprint $table) {
$table->increments('id');
$table->longText('content');
$table->longText('answer')->nullable();
$table->boolean('is_publish')->default(0);
$table->timestamps();
});
我以簡單的形式添加了列,您可以根據自己的項目添加..
第二個是'post_comment_user',用于包含帖子和用戶與評論和答案的關系。這樣的遷移
Schema::create('post_comment_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('post_id')->unsigned();
$table->integer('comment_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
$table->foreign('comment_id')->references('id')->on('comment_answer')->onDelete('cascade');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
我只是建立了關系,如果你愿意,你也可以為用戶使用“comment_answer”表
然后,您可以像這樣在模型文件(“帖子”)中為帖子添加評論;
public function get_comments(){
return $this->belongsToMany('App\Models\comment_answer',
'post_comment_user',
'post_id',
'comment_id')
->where('is_publish',1)
->orderBy('created_at');
和這樣的控制器;
$posts=post::where('slug',$post_slug)
->with('get_comments')
->where('is_publish',1)
->firstOrFail();
和這樣的刀片文件;
@foreach($posts->get_comments as $comment)
{{$comment->content}}
{{$comment->answer}}
@endforeach

TA貢獻1909條經驗 獲得超7個贊
子評論應該只是更多評論,除非它們被映射到另一個評論。
創建一個comment_children 表。
結構應該是:
id: BIGINT comment_id: BIGINT child_id: BIGINT
然后你可以在你的 Comment 模型上創建一個 hasManyThrough 子關系,并使用 comment_children 表來匹配它們。
這將允許您急切加載子評論,您可以通過添加使您的模式始終這樣做:
protected $with = [‘children’]
您還需要在 PostStatus 模型上建立評論關系。
還可以通過添加以下內容來設置您的模型以始終加載此關系:
protected $with = [‘comments’]
現在,每當您獲取帖子時,該集合將始終包含所有評論和所有子項。
現在要訪問它,例如:
$post = Post::where(‘id’, 1)->first()
在你的刀片中:
@foreach($post->comments as $comment)
// display comment
@foreach($comment->children as $child)
// display child comments
@endforeach
@endforeach
- 2 回答
- 0 關注
- 129 瀏覽
添加回答
舉報