Count the Number of Entries in an Ecto Repository

拥有回忆 提交于 2019-12-06 16:38:02

问题


Whats the quickest way to see the number of entries in my database? I'd like to see the number of posts in my posts/index view.

Say I have a Post model and a bunch of posts saved in my database. In Rails I could do something like this in a view file:

<h1><%= @posts.length %> Posts</h1>

or

<h1><%= @posts.size %> Posts</h1>

or

<h1><%= @posts.count %> Posts</h1>

What's the Phoenix Framework/Elixir equivalent?


回答1:


If you've already loaded the posts in memory in your controller using Repo.all, you can use length/1 to count the number of items in the list. This is equivalent to .length in Ruby/Rails.

length(@posts)

If you want to run the count query in the database instead, you can do:

Repo.one(from p in Post, select: count("*"))

You can also add where: filter to the query to restrict the posts to e.g. created by a specific user. This is equivalent to doing .count in Rails.




回答2:


The options that Dogbert has provided are both correct and should be used for Ecto 1.x.

In Ecto 2.0 you can use Repo.aggregate/4

Repo.aggregate(Post, :count, :id)


来源:https://stackoverflow.com/questions/36683238/count-the-number-of-entries-in-an-ecto-repository

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!