用于连接具有反向关系的三个表中的数据的 SQL 查询
我有三个表:玩家、游戏、隐藏
这是玩家模型
has_many :hides, :foreign_key=> "hider_id",
:dependent => :destroy
has_many :hidees, :through => :hides
这是属于隐藏模型的属性。
attr_accessible :hidee_id
belongs_to :hider, :class_name => "Player"
belongs_to :hidee, :class_name => "Game"
validates :hider_id, :presence => true
validates :hidee_id, :presence => true
这是游戏模型:
has_many :reverse_hides, :foreign_key => "hidee_id",
:class_name => "Hide",
:dependent => :destroy
has_many :hiders, :through => :reverse_hides
我想编写一个查询来返回当前玩家隐藏的所有游戏。
目前我有: Game.joins(:hiders)
它返回所有标记为隐藏的游戏,我需要做什么才能找到仅被特定玩家隐藏的游戏...例如where('Player.id = ?' hider_id) <-- 这似乎不起作用。
我感谢您的帮助和时间!
I have three tables: player, games, hide
Here is the Player model
has_many :hides, :foreign_key=> "hider_id",
:dependent => :destroy
has_many :hidees, :through => :hides
Here are the attributes belonging to the Hide Model.
attr_accessible :hidee_id
belongs_to :hider, :class_name => "Player"
belongs_to :hidee, :class_name => "Game"
validates :hider_id, :presence => true
validates :hidee_id, :presence => true
Here is the Games model:
has_many :reverse_hides, :foreign_key => "hidee_id",
:class_name => "Hide",
:dependent => :destroy
has_many :hiders, :through => :reverse_hides
I want write a query that would return all games that were hidden by the current player.
At present I have: Game.joins(:hiders)
which returns all games that are marked as hidden, what do i need to do to find the games only hidden by a particular player... for example where('Player.id = ?' hider_id) <-- this did not seem to work.
I appreciate your help and time!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当然,这并没有利用太多 Rails 的魔力,但如果我正确理解了你的模型,它应该可以工作:
Granted this doesn't take advantage of much Rails magic, but it should work, if I've understood your models properly: