如何使用 ActiveRecord 或 Mongoid 编写此查询?

发布于 2024-12-26 06:15:31 字数 286 浏览 2 评论 0原文

Mongoid 和 ActiveRecord 的接口非常相似,所以我认为 或 都可以工作。我需要一个查询来满足以下条件。

我需要知道过去 10 天内食用某种特定类型谷物的天数。麦片一天可以吃 10 次,但我只需要知道这一天至少有 1 次麦片被吃过。因此,如果今天是 11 号,并且用户在 5 号吃了 2 次 Fruity Pebbles,7 号吃了 10 次,8 号吃了一次,那么答案仍然是 3。

如何执行类似于 ActiveRecord 或 Mongoid 的查询?假设基类是“Cereal”并且有一个名为“type”的字段

Both of the interfaces for Mongoid and ActiveRecord are similar enough so I think either or will work. I need a query to meet the following criteria.

I need to know the number of days a particular type of cereal has been eaten in the last 10 days. The cereal can be eaten 10 times in one day, but I only need to know that the day has had at least 1 time that the cereal was eaten. So if today is 11th, and a user has eaten Fruity Pebbles 2 times on the 5th, 10 times on the 7th, and once on the 8th, the answer is still 3.

How does one perform a query similar to that with ActiveRecord or Mongoid? Assume the base class is 'Cereal' and there is a field named 'type'

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

水波映月 2025-01-02 06:15:31

不确定我是否理解了。 Cereal.where(:last_eaten.gt => Date.today - 10.day) 或者 mongoid 中类似的东西?我在这里凭着我的勇气,可能不完全正确

Not sure I understood. Cereal.where(:last_eaten.gt => Date.today - 10.day) or something like that in mongoid ? I'm going with my guts here, might not be completely correct

豆芽 2025-01-02 06:15:31

如果没有正确的模型样本,很难回答。

如果你的模型符合我的想法(类似于凯特的答案),这可能会起作用:

Cereal.where("date > ?", Date.today - 10.days).select("distinct(date)").count

你可能需要稍微调整一下,但这本质上就是你必须做的。

It's difficult to answer without a proper sample of your model.

This could work if your model fits what I have in mind (similar to Katen's answer):

Cereal.where("date > ?", Date.today - 10.days).select("distinct(date)").count

You might have to tweak it a bit, but that's essentially what you have to do.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文