Rails过滤多对多关系中的记录 [英] Rails filtering records in many to many relationship
本文介绍了Rails过滤多对多关系中的记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我与书籍和作者之间有很多联系,例如:
I have many to many relationship for books and authors like:
class Book < ApplicationRecord
has_many :books_authors, inverse_of: :author, dependent: :destroy
has_many :authors, through: :books_authors
end
class Author < ApplicationRecord
has_many :books_authors, dependent: :destroy
has_many :books, through: :books_authors
end
class AuthorsBook < ApplicationRecord
belongs_to :author
belongs_to :book
end
现在获取所有图书
,其中个作者
的 id:1和3
查询类似于:
Now to get all the Books
with Authors
of ids: 1 and 3
The query is like :
Book.joins(:authors).where(authors: {id: [1, 3]}).uniq
Book.joins(:books_authors).where(books_authors: {author_id: [1,3]}).uniq
Book.joins(:authors).where('authors.id IN (?)', [1,3]).uniq
但是我得到一本书的作者ID为 2,3,5
,但事实并非如此,因为它没有 author
id 1
。
But I get a book whose authors' ids are 2,3,5
, which should not be the case, as it does not have author
with id 1
.
所以,我怎么能具有给定作者ID的书?
So , how could I only get the books with given authors ids?
推荐答案
您需要具有
子句在那里结合您的where子句:
You need a having
clause in there combined with your where clause:
ids = [1,3]
Book
.select('books.*') # not sure if this is necessary
.where(authors_books: { author_id: ids })
.joins(:authors_books)
.group('books.id')
.having('count(authors_books) >= ?', ids.size)
SQL: https://www.db-fiddle.com/f/i7TXPJgavLwQCHb4GhgH3b/0
这篇关于Rails过滤多对多关系中的记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文