从表中过滤过时的项

zpgglvta  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(253)

我的应用程序是使用ruby on rails构建的,由mysql db支持,它有两个表(模型)-product(id、name、created\u at、updated\u at等)和product\u details(id、product\u type、product\u id、expires\u on、created\u at、updated\u at等)(通过product id列连接)。
我只需要从产品模型/表中选择满足以下条件之一的活动记录或产品标识-该特定产品的产品详细信息已过期/过期(expires\u on列显示在product\u details表中)或product\u details表中根本没有该产品的条目(在我的应用程序中有效的方案)(用例)
请注意,product\ id是一个外键,它引用product(id)
非常感谢您的帮助。提前谢谢!:)

sxpgvts3

sxpgvts31#

假设:

class Product < ApplicationRecord
  has_one :product_detail
end

class ProductDetail < ApplicationRecord
  belongs_to :product
end

您可以使用简单的单行查询来获取过期产品或没有详细信息的产品:

Product.select { |p| p.product_detail.nil? || p.product_detail.expires_on <= Date.today }

相关问题