基于计算字段进行查询

基于计算字段进行查询

本文介绍了使用 Mongoid 基于计算字段进行查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在模型 Invoice 中实现范围 overdue 以返回所有超过日期的发票,直到必须支付为止.我有字段 invoice_date, :type =>日期days_for_payment, :type =>整数.

I want to implement a scope overdue in a model Invoice to return all invoices that exceeded the date, until they had to be paid. I have the fields invoice_date, :type => Date and days_for_payment, :type => Integer.

在我以前基于 ActiveRecord 构建的版本中,我可以使用查询

In my previous version, which was built on ActiveRecord, I could use the query

Invoice.where("invoice_date + days_for_payment < ?", Date.today)

此查询在 DB 端进行计算.

This query made the calculation on the DB side.

有没有办法用 Mongoid 完成同样的事情?或者有人知道一个好的解决方法(proc、lambda 等)吗?

Is there a way to get the same thing done with Mongoid? Or does anyone know a good workaround (proc, lambda, etc.)?

我使用 mongoid '2.4.12'

I use mongoid '2.4.12'

推荐答案

我自己找到了答案.使用前缀 this.* 我可以引用字段.我可以使用 JavaScript 函数.MongoDB 变得越来越酷!

Found the answer myself. With the prefix this.* I can reference to the fields. And I can use JavaScript functions. MongoDB gets cooler and cooler!

所以这是我的解决方案:

So here is my solution:

class Invoice
  include Mongoid::Document
  field :invoice_date, :type => Date
  field :days_for_payment, :type => Integer
  ...

  scope :overdue, where("(Math.round(this.invoice_date.getTime() / 1000) + (this.days_for_payment * 24 * 3600)) < #{Time.now.to_i}")

  ...
end

js 中的时间戳创建工作不同.所以我不得不去掉最后三个数字并将它们四舍五入.如果有人知道更优雅的方式,请告诉我.

Timestamp creation in js works different. So I had to get rid of the last three numbers and round them.If anybody knows a more elegant way, please let me know.

我剩下的唯一问题是,我无法将 Date 对象存储到 MongoDB.它总是告诉我必须使用 Time.我想我最好将 mongoid 升级到 3.0.1.

My only problem left is, that I can't store a Date object to MongoDB. It always tells me I have to use Time. I think I better upgrade mongoid to 3.0.1.

这篇关于使用 Mongoid 基于计算字段进行查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 06:34