代码之家  ›  专栏  ›  技术社区  ›  jspooner Ryan Bigg

ActiveRecord:无关联查找

  •  0
  • jspooner Ryan Bigg  · 技术社区  · 17 年前

    我有一个 many_to_many ImageShell和用户之间的关系。我需要找到所有没有用户的ImageShell。

    我有一个查询可以找到它们,但如何将其放入 named_scope ?

    SELECT * FROM image_shells INNER JOIN image_shells_users ON (image_shells_users.image_shell_id!=image_shells.id)
    
    
    class ImageShell < ActiveRecord::Base
       has_and_belongs_to_many :riders, :class_name => "User"
    end
    
    class User < ActiveRecord::Base  
      has_and_belongs_to_many :image_shells
    end
    

    我可以使用SQL查找,但这很混乱。

    img_shells_with_out_users = ImageShell.find_by_sql 'SELECT * FROM image_shells INNER JOIN image_shells_users ON (image_shells_users.image_shell_id!=image_shells.id)'
    
    3 回复  |  直到 17 年前
        1
  •  8
  •   Peer Allan    17 年前

    应该做这个把戏

    named_scope :without_users, { :include => :users, 
       :conditions => 'image_shell_users.user_id IS NULL' } 
    

    使用include选项时,ActiveRecord负责为您生成所有正确的连接。为了包括用户,它必须通过联接表,这样您就可以在您的条件中使用它。

        2
  •  1
  •   jspooner Ryan Bigg    17 年前

    超级易

      named_scope :with_out_users, {
    :select => "image_shells.*",
    :joins => "INNER JOIN image_shells_users ON (image_shells_users.image_shell_id!=image_shells.id)" 
      }
    
        3
  •  0
  •   Shadwell    17 年前
    named_scope :without_users, 
      :conditions => "not exists (select * from image_shells_users where
                      image_shell_users.image_shell_id = image_shells.id)"
    

    您在问题中提供的SQL在没有用户的情况下实际上找不到图像外壳,它实际上将图像外壳连接到 每一个 数据库中的用户,该用户具有图像外壳程序,但您正在查询的图像外壳程序除外。