Laravel-按created_at线程表中的帖子表中的日期排序


Laravel - Orderby created_at date in posts table from threads table

我有一个帖子和线程表。我的关系是:posts.thread_id = threads.id

我正在尝试创建一个包含许多帖子的论坛。我想按帖子中的created_at日期对列表进行排序。

所以:我创建了一个新帖子,它现在链接到一个线程。当我转到论坛的主页时,它应该使用每个线程中的更新帖子对线程进行排序。换句话说,这类似于当有人回复堆栈溢出中的线程时,它会到达顶部。

我希望这是有道理的。

我在Thread.php的关系

public function posts()
{
    return $this->hasMany('App'Forum'Post', 'thread_id', 'id');
}

Post.php关系

  public function thread()
{
    return $this->belongsTo('App'Forum'Thread', 'thread_id', 'id');
}

我的代码来排列线程:

$threads = Thread::all();

它只是按其ID的顺序显示线程。 请帮忙。任何帮助都非常感谢。

试试这个:

public function posts()
{
    return $this->hasMany('App'Forum'Post', 'thread_id', 'id')->orderBy('created_at', 'desc');
}

编辑

实际上,在进一步阅读您的问题后,我认为您的追求是:

 protected $touches = array('threads');

将此行包含在您的 Post 模型中。这将更新相关模型上的时间戳。然后,您可以按updated_at列对线程进行排序。

$threads = Thread::latest('updated_at')->take(5)->get()

将"updated_at"字段替换为要用于检查最新线程的任何字段。将"5"更改为您要抓取的任意数量。或使用 paginate()。

这应该适用于一对多关系:

$posts = Post::orderBy('created_at', 'desc')->take(10)->get();

在视图中:

@foreach ($posts as $post)
    {{ $post->thread->title }}
@endforeach