Paginating in the Database
As usual, we start with adding the new functionality to our Meerkats context. Open up lib/meow/meerkats.ex and add the following code:
| def list_meerkats_with_total_count(opts) do |
| query = from(m in Meerkat) |> filter(opts) |
| |
| total_count = Repo.aggregate(query, :count) |
| |
| result = |
| query |
| |> sort(opts) |
| |> paginate(opts) |
| |> Repo.all() |
| |
| %{meerkats: result, total_count: total_count} |
| end |
| |
| defp paginate(query, %{page: page, page_size: page_size}) |
| when is_integer(page) and is_integer(page_size) do |
| offset = max(page - 1, 0) * page_size |
| |
| query |
| |> limit(^page_size) |
| |> offset(^offset) |
| end |
| |
| defp paginate(query, _opts), do: query |
As you can see, we create a new
Get Building Table Views with Phoenix LiveView now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.