【问题标题】:Getting all records where association count is lower than a column value [closed]获取关联计数低于列值的所有记录[关闭]
【发布时间】:2021-02-08 13:43:02
【问题描述】:

我有两个模型:

class Dish
  # column maximum_portions:int

  has_many :portions
end

class Portion
  belongs_to :dish
end

我需要的是获得所有份量少于最大份量的菜肴。

我尝试了 group by 和 have,但没有任何效果。

你能帮帮我吗? :)

【问题讨论】:

  • 能否提供示例数据和所需的输出。

标签: sql ruby-on-rails activerecord


【解决方案1】:
Dish.left_join(:portions)
    .group("dishes.id")
    .having("COUNT(portions.id) < dishes.maximum_portions") 

如果您想要包含 0 个部分的菜肴并使用至少 1 个部分进行连接(产生 INNER JOIN),请使用 left_join。

PS:下一次,提供样本数据,让事情变得更容易;)

【讨论】:

    猜你喜欢
    • 2013-12-09
    • 1970-01-01
    • 1970-01-01
    • 2015-10-10
    • 1970-01-01
    • 1970-01-01
    • 2013-02-14
    • 2022-11-04
    • 1970-01-01
    相关资源
    最近更新 更多