代码之家  ›  专栏  ›  技术社区  ›  alavni shubham

Ruby on Rails 5-查找没有关联的实例[关闭]

  •  0
  • alavni shubham  · 技术社区  · 7 年前

    我想找到没有订单的产品。我怎么找到他们?

    class Order < ApplicationRecord
       belongs_to :user
       belongs_to :address
       has_many :line_items, dependent: :destroy
       has_many :products, through: :line_items
    end
    
    class Product < ApplicationRecord
      validates_presence_of :name
      has_many :line_items
      has_many :orders, through: :line_items 
    end
    
    class LineItem < ApplicationRecord
      belongs_to :order
      belongs_to :product
    end
    
    3 回复  |  直到 7 年前
        1
  •  4
  •   max Mike Williams    7 年前
    Product.left_outer_joins(:line_items).where(line_items: { id: nil })
    

    这将返回中没有关联行的产品 line_items 表-这实际上意味着它们没有关联的订单。

    这应该比SELECT DISTINCT查询性能更好,因为您不需要获取一堆ID来用于求反。

        2
  •  0
  •   sachin bhoi    7 年前

    请尝试以下查询。我想这应该对你有帮助。

    Product.includes(:line_items).where(line_items: { id: nil })
    

    Product.includes(:line_items).where(line_items: {product_id: nil})
    
        3
  •  0
  •   Ganesh    7 年前

    请尝试以下查询,因为您使用了产品和订单之间的多对多关系

    Product.where('id NOT IN (SELECT DISTINCT(product_id FROM line_items))')
    

    我希望这对你有用。