【问题标题】:Join two tables with condition - ruby on rails加入两个有条件的表 - ruby​​ on rails
【发布时间】:2013-09-17 09:49:56
【问题描述】:

我想加入 2 张桌子、游戏和游戏日志。我是这样做的:

game_joins =  Game.joins(:game_logs)

成功了。但问题是我只想加入 player_id = 1 的地方(例如)。列 player_id 只能在表 game_logs 中找到。所以,当我这样做时:

game_joins =  Game.joins(:game_logs).where(:player_id => 1)

找不到列player_id,因为

Game.joins(:game_logs)  

结果:

SELECT games.* FROM games
  INNER JOIN game_logs ON game_logs.game_id= game.id

所以,问题是我必须使用来自 table game_logs 的条件过滤 game_joins 的可能性是什么。我希望我解释得足够好。谢谢

【问题讨论】:

    标签: mysql ruby-on-rails-3 activerecord join


    【解决方案1】:
    game_joins =  Game.joins(:game_logs).where(:game_logs => { :player_id => 1 })
    

    【讨论】:

      【解决方案2】:

      在你需要的模型 GameLog 中

       belongs_to :game
      

      在你需要的模型游戏中

       has_many :game_logs
      

      那么修改查询的一种方法是

       game_joins =  Game.joins("left join game_logs on games.id = game_logs.game_id").where("game_logs.player_id = 1").all
      

      或者你可以使用

        game_joins =  Game.joins(:game_logs).where("game_logs.player_id = 1").all
      

      【讨论】:

        猜你喜欢
        • 2014-09-24
        • 1970-01-01
        • 2014-09-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多