rails mongoid 标准按关联查找 [英] rails mongoid criteria find by association

查看:23
本文介绍了rails mongoid 标准按关联查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过包含在belongs_to 关系中的关联用户名查找记录,但它不起作用.

I'm trying to find a record by associated username which is included in a belongs_to relation, but it's not working.

文章属于用户用户有很多文章

Articles belong to Users Users have many articles

Article.where(user_id: someid) 工作正常,但我想使用存储在用户表中的用户名作为参考.

Article.where(user_id: someid) works fine, but I'd like to use the username as reference which is stored in the Users table.

Article.includes(:user).where(:username => "erebus")
Article.includes(:user).where("user.username" => "erebus")

我也有 identity_map_enabled: true

Article.includes(:user).inclusions 返回关系细节

不起作用,我有什么不明白的?

Doesn't work, what am I not understanding?

推荐答案

你必须记住,mongodb 中没有连接.在关系数据库中,includes 形成一个连接查询,您可以在查询中使用两个表中的列.然而,由于在 mongodb 中没有连接,同样是不可能的.

You have to keep in mind that there are no joins in mongodb. In relational dbs, includes forms a join query and you can use columns from both the tables in query. However due to absence of joins in mongodb, same is not possible.

在 mongoid 中,includes 只是节省了一堆 db 调用.它在身份映射中获取并存储关联记录以进行快速检索,但仍然在查询时,一个查询只能处理一个集合.

In mongoid, includes just saves a bunch of db calls. It fetches and stores the associated records in identity map for fast retrieval, but still while querying, one query can only deal with one collection.

如果您需要基于用户名的文章,我建议您解决以下问题:

If you need articles based on user names, I would suggest following work around:

user_ids = User.where(username: 'erebus').only(:_id).map(&:_id)
articles = Article.where(:user_id.in => user_ids)

这篇关于rails mongoid 标准按关联查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆