[英]Rails 3 has many through query all parent records and only include children that meet conditions
我有一种关系,即餐馆可以通过一个名为action的中间表来拥有许多用户,而用户也可以通过action来拥有许多餐馆。
我正在尝试查询所有餐厅,仅包括满足某些条件的用户; 无论是否有符合搜索条件的用户,或者根本没有与该餐厅相关联的用户,都应返回该餐厅。 我的模型如下。
餐厅型号:
has_many :actions
has_many :users, through: :actions
动作模型:
belongs_to :user
belongs_to :restaurant
用户模型:
has_many :actions
has_many :restaurants, through: :actions
在这种情况下,您需要使用左外部联接。 如果仅创建联接以查找具有特定属性的用户,例如:
Restaurant.joins(:users).where("users.name LIKE 'user_name'")
内部连接是隐式创建的,它将使所有餐厅都没有用户。 要包括它们,请执行以下操作:
Restaurant.joins(["LEFT OUTER JOIN actions on restaurants.id = actions.user_id", "LEFT OUTER JOIN users on users.id = actions.user_id"]).where("users.name LIKE 'James' OR users.name IS NULL ")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.