如何实现 mongodb 'includes?'取景器条件
我正在使用 Mongoid 并有一个项目和一个用户模型。 在项目模型中,我有一个字段
class Project
include Mongoid::Document
field :name
field :user_ids, :type => Array
end
class User
include Mongoid::Document
field :email
end
,我可以找到属于一个项目的所有用户,即“查找该项目的用户”,
@project = Project.first # => 'Housework'
User.criteria.id(@project.user_ids) # => ['Bart','Lisa','Maggie']
但是我在查找属于一个用户的所有项目时遇到了一些麻烦,即“查找该用户的用户” 我知道您
@user = User.first # => 'Bart'
Project.where(:user_ids => @user.id) # doesn't work
Project.where(:user_ids.includes => @user.id) # not such method
Project.where(:user_ids => [@user.id]) # doesn't make sense to compare arrays, but tried anyway and doesn't work
可以在用户模型中使用另一个字段来存储project_ids,我很乐意这样做,但我只是很好奇,是否有一种在查找条件中使用的方法与#includes 类似?在红宝石中?
I am using Mongoid and have a project and a user model.
in the Project model, I have a field
class Project
include Mongoid::Document
field :name
field :user_ids, :type => Array
end
class User
include Mongoid::Document
field :email
end
I can find all the users belonging to one project, i.e., 'find this project's users'
@project = Project.first # => 'Housework'
User.criteria.id(@project.user_ids) # => ['Bart','Lisa','Maggie']
But I am having a bit trouble finding all the projects belonging to one user, i.e, 'find this user's projects'
@user = User.first # => 'Bart'
Project.where(:user_ids => @user.id) # doesn't work
Project.where(:user_ids.includes => @user.id) # not such method
Project.where(:user_ids => [@user.id]) # doesn't make sense to compare arrays, but tried anyway and doesn't work
I know that you can have another field in the User model to store project_ids, I would gladly do that, but I am just curious, is there a method to be used in finder conditions that works similarly to #includes? in ruby?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我找到了解决这个问题的方法。这是 all_in finder 方法
示例:
要查找“colors”数组字段中颜色为红色的所有水果,可以查询:
=>[apple, pineapple]
I found a solution to this. it is the all_in finder method
example:
To find all fruits that have the color red in their 'colors' array field, one can query:
=>[apple, pineapple]