Rails过滤多对多关系中的记录

时间:2019-01-18 19:48:06

标签: sql ruby-on-rails postgresql ruby-on-rails-5 ruby-on-rails-5.2

我与诸如此类的书籍和作者有很多联系

var main = function() {
    "use strict";
    var addTodosToList = function(todos) {
        var todolist = document.getElementById("todo-list");
        for (var key in todos) {
            var li = document.createElement("li");
            li.innerHTML = "TODO: " + todos[key].message;
            todolist.appendChild(li);
        }
    };
    $.getJSON("todos", addTodosToList);
}
$(main);

现在获取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 中的BooksAuthors中的所有ids: 1 and 3 查询就像:

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的书。

那么,我怎么只能获得具有给定作者ID的书?

1 个答案:

答案 0 :(得分:2)

其中需要一个having子句以及where子句:

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