简体   繁体   English

Rails mysql:如何查询具有深层嵌套关系的表(has_many和belongs_to)?

[英]Rails mysql: How to query tables with deeply nested relations(has_many and belongs_to)?

I have the following models: 我有以下型号:

class User < ActiveRecord::Base
  has_many :keys
end

class Key < ActiveRecord::Base
  belongs_to :room
end

class Room < ActiveRecord::Base
  belongs_to :building
end

class Building < ActiveRecord::Base
  #Has column "name"
end

I want to get all users that have keys that belong to a building with the name "HQ" 我想获取所有具有属于“ HQ”名称的建筑物的钥匙的用户

Bassicaly something like this(pseudo query): 像这样的basicaly(伪查询):

Users = users.where('keys.room.building.name=?', name)

This is the furthest I got: 这是我得到的最远的信息:

users = User.joins(:keys).where('keys.room.building.name=?', name)

But it gives the following error: 但是它给出了以下错误:

ActionView::Template::Error (Mysql2::Error: You have an error in your SQL syntax; 
check the manual that corresponds to your MySQL server version for the right syntax to use near '.name='HQ')' at line 1: 
SELECT `users`.* FROM `users` INNER JOIN `keys` ON `keys`.`user_id` = `users`.`id` WHERE (keys.room.building.name='HQ')):

试一下

User.joins(keys: [room: :building]).where("buildings.name" => name)

Try this:- 尝试这个:-

User.joins(:keys => {:room => {:building}}).where("buildings.name" => name)

Assuming you also want to eager load avoid 1+N queries: 假设您还希望避免加载1 + N个查询:

User.includes(:keys => {:room => {:building}}).where("buildings.name" => name)

Hope this is useful to you!! 希望这对您有用!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 查询两个表之间的belongs_to / has_many关系 - Query on two tables with belongs_to/has_many relation 如何为此逻辑编写一个SQL查询(has_many,belongs_to关联)? - How to write a SQL query for this logic (has_many, belongs_to association)? 自定义数据库ActiveRecord :: AssociationTypeMismatch上的Rails has_many / belongs_to得到了Fixnum - Rails has_many/belongs_to on custom database ActiveRecord::AssociationTypeMismatch got Fixnum 更改Rails belongs_to,has_many默认选择(Where)语句 - Changing Rails belongs_to, has_many default Select (Where) Statement Rails Emirates_to和has_many没有创建主外键关系 - Rails belongs_to and has_many is not creating a primary foreign key relation 通过named_scope返回对象数组 - has_many ... belongs_to association; UNION ALL查询 - Returning array of objects via named_scope — has_many…belongs_to association; UNION ALL query 具有主要BELONGS_TO的HAS_MANY的关系数据库设计 - Relational Database design for HAS_MANY with a primary BELONGS_TO 数据库驱动的应用程序中的Has_Many,Belongs_To关系 - Has_Many, Belongs_To Relationship in a Database Driven Application 您如何通过关系来使Rails has_many与has_many条件一起工作? - How do you get Rails has_many through relations to work with has_many conditions? Ruby on Rails:两种模型都有Has / Many和Belongs_to - Ruby on Rails: Two Models Both Have Has/Many and Belongs_to
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM