我有这样的简单类:
class Book
has_many :book_categorizations
has_many :categories, through: :book_categorizations, source: :book_category
end
class BookCategorizations
belongs_to :book
belongs_to :book_category
end
class BookCategory
has_many :book_categorizations
has_many :books, through: :book_categorizations
end
我想找到没有类别的Book
。如何使用where
查询?
答案 0 :(得分:3)
您可以将scope
添加LEFT JOIN
到您的模型中:
# in book.rb
scope :without_categories, lambda {
joins('LEFT JOIN book_categorizations ON books.id = book_categorizations.book_id').
where(book_categorizations: { book_category_id: nil })
}
可以使用:
Book.without_categories
#=> returns books without a category
工作原理:
成像您有一个fruits
和一个colors
表:
fruits
id | name
1 | Apple
2 | Orange
3 | Banana
colors
id | name
1 | black
2 | red
3 | yellow
和colors_fruits
联接表:
colors_fruits
color_id | fruit_id
2 | 1 # red Apple
3 | 3 # yellow Banana
自从Rails' joins
方法生成INNER JOIN
,所有连接只会返回至少有一种颜色的水果。橙色不在列表中,因为它没有颜色(因此无法连接):
Fruit.joins(:colors)
#=> red Apple, yellow Banana (simplified)
但是当我们对没有颜色的水果感兴趣时,我们需要一个LEFT JOIN
。 LEFT JOIN
包括左表中的所有元素 - 即使右表没有匹配(遗憾的是这种连接没有Rails助手):
Fruits.joins('LEFT JOIN colors_fruits ON colors_fruits.fruits_id = fruits.id')
这会产生如下结果:
id | color | fruit_id | color_id
1 | Apple | NULL | NULL
2 | Orange | 2 | 1
3 | Banana | 3 | 3
现在我们只需要排除没有color_id
Fruits.joins('LEFT JOIN colors_fruits ON colors_fruits.fruits_id = fruits.id').
where(colors_fruits: { color_id: nil })
您可能想了解不同类型的SQL JOINS
。这是众所周知的diagram about joins。