如何实现 mongodb 'includes?'取景器条件

发布于 2024-09-16 01:29:38 字数 854 浏览 6 评论 0原文

我正在使用 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 技术交流群。

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

发布评论

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

评论(1

望笑 2024-09-23 01:29:38

我找到了解决这个问题的方法。这是 all_in finder 方法

示例:

Fruit.all[0].colors = ['red','green','blue'] #=> apple
Fruit.all[1].colors = ['yellow','green']     #=> banana

Fruit.all[2].colors = ['red', 'yellow']      #=> pineapple

要查找“colors”数组字段中颜色为红色的所有水果,可以查询:

Fruit.all_in(:colors => ['red'])

=>[apple, pineapple]

I found a solution to this. it is the all_in finder method

example:

Fruit.all[0].colors = ['red','green','blue'] #=> apple
Fruit.all[1].colors = ['yellow','green']     #=> banana

Fruit.all[2].colors = ['red', 'yellow']      #=> pineapple

To find all fruits that have the color red in their 'colors' array field, one can query:

Fruit.all_in(:colors => ['red'])

=>[apple, pineapple]

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