簡體   English   中英

如何在Rails類模型范圍內編寫格式為“ SELECT…FROM…WHERE…IN(SELECT…)”的SQL?

[英]How do I write SQL with format 'SELECT … FROM … WHERE … IN ( SELECT … )' in rails class model scope?

我如何用

SELECT * 
FROM tableA 
WHERE tableA.col1 IN (
  SELECT tableB.col2 
  FROM tableB
)

在Rails模型范圍內?

當前,我在ruby模型文件中有一個像這樣的SQL作為類方法:

class Book
  def self.select_list_for_current_project_fund_schemes_sponsor_name
    Books.connection.select_all('
      SELECT book.name, book.name 
      FROM BOOK b
      WHERE b.b_pk IN (
        SELECT s.b_fk
        FROM STORE s
      )
    ').rows
  end
end

它有效,並產生我想要的輸出:

Book.select_list_for_current_project_fund_schemes_sponsor_name
=> [[book_name1, book_name1], [book_name2, book_name2], [book_name3, book_name3]...]

但是我想在范圍內編寫它,使其與其他代碼一致。

如何在類模型范圍內使用ActiveRecord的“ where”方法編寫上述SQL?

我想要在類的模型文件中這樣的內容:

class Book
  scope :books_in_store_that_exist, -> { where(magic_sql_wrapped_in_ruby_here) }

  # more code here...
end

注意:我沒有商店模型,只有書本模型。

換句話說,我希望能夠通過編寫來實現相同的輸出

Book.books_in_store_that_exist.select(:name).map {|b| [b.name, b.name]}
=> [[book_name1, book_name1], [book_name2, book_name2], [book_name3, book_name3]...]

在這種情況下,您只需要添加一個內部聯接

class Book
  scope :books_in_store_that_exist, -> { joins("INNER JOIN stores ON books.b_pk = stores.b_fk") }
end

現在,您可以使用它來鏈接它。

Book.books_in_store_that_exist.select(:name).map { |b| [b.name, b.name] }
#=> [[book_name1, book_name1], [book_name2, book_name2], [book_name3, book_name3]...]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM