【问题标题】:Filtering out the outdated items from table从表中过滤掉过时的项目
【发布时间】:2018-06-27 14:05:14
【问题描述】:

我的应用程序是使用 ruby​​ on rails 构建的,由 mysql DB 支持 它有 2 个表(模型) - product(id, name, created_at, updated_at, etc.) 和 product_details(id, product_type, product_id, expires_on, created_at, updated_at, etc.)(按产品连接ID 列)。

我只需要从满足以下任一条件的产品模型/表中选择那些活动记录或 product_id - 该特定产品的产品详细信息已过时/过期(product_details 表中存在 expires_on 列)或存在在 product_details 表中根本没有该产品的条目(我的用例中的有效场景)

请注意,product_id 是一个引用 product(id) 的外键

非常感谢任何帮助。提前致谢! :)

【问题讨论】:

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


    【解决方案1】:

    假设:

    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 }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-02
      • 2021-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多