Sắp xếp bài viết theo comments gần nhất hoặc thời gian viết bài trong SQL và Laravel


Sắp xếp bài viết theo comments gần nhất hoặc thời gian viết bài trong SQL và Laravel

Sắp xếp bài viết theo comments gần nhất hoặc thời gian viết bài trong SQL và Laravel

Sắp xếp bài viết giống như cách sắp xếp trong các diễn đàn.

Cấu trúc các bảng

Bảng Posts:
$table->increments('id');
$table->string('title');
$table->text('content');
$table->timestamps();
Bảng Comments
$table->increments('id');
$table->integer('post_id')->unsigned();
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
$table->text('content');
$table->timestamps();
Khi đó ta có quan hệ giữa bảng postspost_comments là One to Many.

Sắp xếp trong SQL

SELECT *
FROM posts AS p
LEFT JOIN post_comments AS c on c.post_id = p.id
GROUP BY p.id
ORDER BY COALESCE(GREATEST(p.created_at, MAX(c.created_at)), p.created_at) DESC

Sắp xếp trong Laravel

DB::table('posts')
->leftJoin('post_comments', 'post_comments.post_id', '=', 'posts.id')
->groupBy('posts.id')
->orderByRaw('COALESCE(GREATEST(posts.created_at, MAX(post_comments.created_at)), posts.created_at) DESC')
->select('posts.*')