需要帮助编写mongoid查询。

时间:2022-04-17 02:01:14

Here are my two models

这是我的两个模型。

class Customer
  field: name, type: String
  has_many :calls
end

class Call
  field: number, type: String
  field: call_time, type: DateTime
  belongs_to :customer
end

My requirement: For the above arrangement i.e., A Customer has_many Calls & a Call belongs_to a Customer. I would like to get the List of customers ordered by the latest call of their calls.

我的要求:上述安排即,客户has_many调用&调用belongs_to客户。我想从最近的来电中得到客户的订单。

Let me explain. Say, the database has the following data

让我解释一下。例如,数据库有以下数据。

Customer
John
     Calls
     987     /  10AM
     987     /   9AM
Jack
     Calls
     878     /  11AM
     878    /    6AM
Rohan
     Calls
     990     /  9AM
     990    /   8AM

My expected output would be

我期望的输出是。

Jack
John
Rohan

Since the latest call was from Jack (@11AM), then John (@10AM), then Rohan (@9AM). Now how do I write such a query?

因为最近的电话是Jack (@11AM),然后是John (@10AM),然后是Rohan (@9AM)。那么如何编写这样的查询呢?

1 个解决方案

#1


0  

As far as I understand, if the Call's are not embedded in the Customer document, the only solution is to load all of your customers and then sort them "manually" through Enumerable#sort, something like

据我所知,如果调用没有嵌入到客户文档中,唯一的解决方案是加载所有的客户,然后通过可枚举的#排序“手工”排序。

Customers.where(some_criteria).sort_by { |c| c.calls.first.sort(call_time: -1) }

You might want to take a look at this: Mongoid, how to order_by through a references_one association (and subsequent associations)?

您可能想看看这个:Mongoid,如何通过一个references_one关联(以及随后的关联)来order_by ?

#1


0  

As far as I understand, if the Call's are not embedded in the Customer document, the only solution is to load all of your customers and then sort them "manually" through Enumerable#sort, something like

据我所知,如果调用没有嵌入到客户文档中,唯一的解决方案是加载所有的客户,然后通过可枚举的#排序“手工”排序。

Customers.where(some_criteria).sort_by { |c| c.calls.first.sort(call_time: -1) }

You might want to take a look at this: Mongoid, how to order_by through a references_one association (and subsequent associations)?

您可能想看看这个:Mongoid,如何通过一个references_one关联(以及随后的关联)来order_by ?