新手问题 eager_load 用到了 left outer join,怎么可以设置里面的 on 条件呢

selenium · April 12, 2019 · Last by selenium replied at April 13, 2019 · 993 hits

User.eager_load(:group)

这条语句的 on 条件是 group.user_id = user.id 我想在加一个条件 group.type = 'XXX', 其实数据可以取出来再筛选但是这么做就有点多余了

left_joins 这个方法怎么传入 on 呢

User.eager_load(:group).where(group: {type: 'XXX'})

试试这样?

假设你的 ActiveRecord 是这样的:

class User < ActiveRecord::Base
  has_one :group
end
class Group< ActiveRecord::Base
  belongs_to :user
end

现在可以这么写:

class User < ActiveRecord::Base
  has_one :group, proc{Group.type_xxx}
end
class Group< ActiveRecord::Base
  belongs_to :user
  scope :type_xxx, proc{where "group.type = 'XXX'"}
end

现在User.eager_load(:group),会实现楼主想要的效果,把 Group scope 里的 where 条件在 left outer join 的时候加到 on 条件里

不过注意scope :type_xxx, proc{where "group.type = 'XXX'"} where 里面的 group 实际应该为 Group 数据库的表名

Reply to tinyfeng

这个方法昨天我也看了,但是我这个需求需要传参进去,有什么办法传参进去吗

Reply to selenium

join 条件动态变化的话,eager_load 应该做不到

Reply to tinyfeng

恩,我现在自己拼接 SQL 了

You need to Sign in before reply, if you don't have an account, please Sign up first.