【发布时间】:2021-05-14 13:18:03
【问题描述】:
我有一个话题表,我想在索引页面上显示该话题的最新评论。到目前为止我已经选择了最新的评论并尝试在页面上显示它,但是它只显示整体的最新评论,而不是特定帖子的最新评论
所以我的 ThreadsController 现在看起来像这样,选择所有 cmets 并首先显示最新的。
public function index()
{
$threads = Thread::latest()->paginate(10);
$latestComment = Comment::latest()->first();
return view('threads.index', compact('threads', 'latestComment'));
}
线程模型
public function user()
{
return $this->belongsTo(User::class);
}
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
评论模型
public function user() {
return $this->belongsTo(User::class);
}
public function thread()
{
return $this->belongsTo(Thread::class);
}
public function commentable() {
return $this->morphTo();
}
那么如何从特定线程中选择最新的评论并将其显示在索引上?
编辑:
控制器:
public function index()
{
$threads = Thread::latest()->with('comments')->paginate(10);
return view('threads.index', compact('threads'));
}
索引刀片:
@foreach($threads as $thread)
{{ $thread->latestComment->user->name }}
@endforeach
评论表迁移
public function up()
{
Schema::create('comments', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->string('body');
$table->unsignedBigInteger('commentable_id');
$table->string('commentable_type');
$table->timestamps();
});
}
【问题讨论】:
-
您需要在
Thread和Comments 之间创建一个relationship。 -
@Unflux 是的,他们在我的模型中有关系一直运行良好,但这个问题我真的不知道如何解决
-
你能提供显示你们关系的代码吗?
标签: laravel controller forum