Rails mysql: 如何查询具有深层嵌套关系(has_many 和belongs_to)的表?
Rails mysql: How to query tables with deeply nested relations(has_many and belongs_to)?
我有以下型号:
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
我想获取所有拥有属于名称为 "HQ"
的建筑物的钥匙的用户
基本上是这样的(伪查询):
Users = users.where('keys.room.building.name=?', name)
这是我得到的最远的:
users = User.joins(:keys).where('keys.room.building.name=?', name)
但它给出了以下错误:
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)
试试这个:-
User.joins(:keys => {:room => {:building}}).where("buildings.name" => name)
假设您还想预加载避免 1+N 次查询:
User.includes(:keys => {:room => {:building}}).where("buildings.name" => name)
希望这对你有用!!
我有以下型号:
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
我想获取所有拥有属于名称为 "HQ"
的建筑物的钥匙的用户基本上是这样的(伪查询):
Users = users.where('keys.room.building.name=?', name)
这是我得到的最远的:
users = User.joins(:keys).where('keys.room.building.name=?', name)
但它给出了以下错误:
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)
试试这个:-
User.joins(:keys => {:room => {:building}}).where("buildings.name" => name)
假设您还想预加载避免 1+N 次查询:
User.includes(:keys => {:room => {:building}}).where("buildings.name" => name)
希望这对你有用!!