用于连接具有反向关系的三个表中的数据的 SQL 查询

发布于 2024-12-25 17:15:49 字数 905 浏览 0 评论 0原文

我有三个表:玩家、游戏、隐藏

这是玩家模型

  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 技术交流群。

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

发布评论

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

评论(1

孤城病女 2025-01-01 17:15:49

当然,这并没有利用太多 Rails 的魔力,但如果我正确理解了你的模型,它应该可以工作:

Game.joins('JOIN hides ON hides.hidee_id = games.id').where('hides.hider_id = ?', player.id)

Granted this doesn't take advantage of much Rails magic, but it should work, if I've understood your models properly:

Game.joins('JOIN hides ON hides.hidee_id = games.id').where('hides.hider_id = ?', player.id)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文