获取至少一个关联对象的记录 [英] get record with at least one associated object
问题描述
我在 mongoid 中具有以下架构:
用户有很多任务-has_many:tasks
User has many tasks - has_many :tasks
任务属于用户-属于:user
Task belongs to user - belongs_to :user
我如何只让10位第一位用户完成至少一项任务?
How can I get only 10 first users with at least one task?
类似这样的东西:
User.where(:tasks.ne => [] ).limit(10)
推荐答案
Your problem is that Mongoid's has_many
doesn't leave anything in the parent document so there are no queries on the parent document that will do anything useful for you. However, the belongs_to :user
in your Task
will add a :user_id
field to the tasks
collection. That leaves you with horrific things like this:
user_ids = Task.all.distinct(:user_id)
users = User.where(:id => user_ids).limit(10)
当然,如果您使用的是 embeds_many :tasks
而不是has_many :tasks
,然后您可以根据需要查询users
集合内的:tasks
.太太,这可能会破坏其他东西.
Of course, if you had embeds_many :tasks
instead of has_many :tasks
then you could query the :tasks
inside the users
collection as you want to. OTOH, this would probably break other things.
如果您需要将任务分开放置(即未嵌入),则可以在User
中设置一个计数器来跟踪任务的数量,然后您可以说:
If you need to keep the tasks separate (i.e. not embedded) then you could set up a counter in User
to keep track of the number of tasks and then you could say things like:
User.where(:num_tasks.gt => 0).limit(10)
这篇关于获取至少一个关联对象的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!