计算Ecto存储库中的条目数 [英] Count the Number of Entries in an Ecto Repository

查看:49
本文介绍了计算Ecto存储库中的条目数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看数据库中条目数的最快方法是什么?我想在我的帖子/索引视图中查看帖子的数量.

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.

说我有一个Post模型,并且在数据库中保存了一堆帖子.在Rails中,我可以在视图文件中执行以下操作:

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>

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

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

Phoenix Framework/Elixir等效什么?

What's the Phoenix Framework/Elixir equivalent?

推荐答案

如果您已经使用Repo.all在控制器的内存中加载了帖子,则可以使用length/1来计算列表中的项目数.这等效于Ruby/Rails中的.length.

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("*"))

您还可以在查询中添加where:过滤器,以将帖子限制为例如由特定用户创建.这等效于在Rails中进行.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.

这篇关于计算Ecto存储库中的条目数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆