Phân Trang (Pagination) Trong Express.js Với Sequelize/MySQL
Để implement pagination hoàn chỉnh cho toàn dự án, bạn cần:
So sánh MongoDB vs SQL
MongoDB:
SQL/Sequelize:
Cả hai đều làm cùng một việc: bỏ qua N records đầu tiên và lấy M records tiếp theo.
Giải thích Offset trong Sequelize
Offset là gì?
Offset là số lượng records cần bỏ qua (skip) trước khi bắt đầu lấy data.
Tại sao lại (page - 1)?
Hãy xem ví dụ cụ thể với limit = 10:
SQL Query tương đương
Hàm getPaginatedPosts
1. Cấu trúc cơ bản
2. Build WHERE clause
3. Build INCLUDE với conditions
4. findAndCountAll - Lấy data + count
Tại sao cần distinct: true?
5. Return pagination metadata
Tính totalPages:
Sử dụng hàm getPaginatedPosts trong Routes / Controller
Tại sao cần baseUrl trong pagination.ejs?
Vấn đề
Pagination component cần tạo links cho các trang, nhưng URL structure khác nhau tùy context:
Giải pháp: baseUrl
Trong pagination.ejs
Ví dụ cụ thể
Scenario 1: Homepage posts
Scenario 2: Category posts
Scenario 3: Tag posts
Pagination Logic Chi Tiết
Hiển thị window của pages
Ví dụ với totalPages = 20, currentPage khác nhau:
Dots (ellipsis) logic
Best Practices
1. Validate page number
2. Set reasonable limits
3. Cache total count
4. SEO: Canonical URLs
Tham khảo thêm
This embedded link can't be shown.
This embedded link can't be shown.
