2016-12-29 39 views
0

可以说我有2种型号:如何基于没有特定值的关联进行查询?

class User 
has_many :books 
end 

class Book 
belongs to :user 
end 

,让我们说,书中有一个字段:标题。

如何查询没有标题为“abc”的图书的用户?

我试过如下:

User.left_outer_joins(:books).group("users.id, books.title").having("COUNT(books.title) = 0 or books.title != #{title}") 

与此查询的问题是,如果用户有2本书(“ABC”和“XYZ”),它仍然会返回。

任何想法?

+0

尝试'User.joins(:书籍).merge(Book.where.not(标题:“ABC '))' – Thanh

+0

所以你想说,如果任何用户在他的集合中甚至只有一个预定名为'abc'的名字,他的名字不应该在结果中,我的理解是否正确?准确地说是 – sahil

+0

。我不想要任何拥有名为abc的书的用户。 –

回答

0

查看下面应该工作

User.joins(:books).group('books.user_id') 
.having("SUM(IF(books.title = 'abc',1,0)) = ?", 0) 

其中基本上只有用户有零书与'abc'的标题。

+0

这个工作几乎正确,但你是最接近的一个:) –

+0

解决方案是用left_outer_join替换连接:User.left_outer_joins(:books).group('books.user_id')。having(“SUM(IF(books.title = 'abc',1,0))=?“,0) –

+0

否则,你不会得到没有任何书的用户。 –

0

试试吧

User.joins(:book).where("books.title !=?","#{title}") 

生成的查询可以在rails console作为

User.joins(:book).where("books.title !=?","#{title}").explain 

See the Documentation

0

也许最简单的方法是:

  • 随着书籍

    book = Book.where(title: 'abc').first 
    user_id = book.user.id 
    User.where.not(id: user_id) 
    
  • uniq的标题没有在书的uniq标题

    books = Book.where(title: 'abc') 
    users_ids = books.map { |b| b.user.id } 
    User.where.not(id: users_ids) 
    
  • 如果你想与基和具有做,那么你需要一个SQL像

    select users.id, IF(title = 'abc',1,0) has_book 
    from users 
         left join books b on user_id = users.id 
    group by id 
    having sum(has_book) = 0 
    

    与AR

    ​​

我希望它是有用的:)

相关问题