簡體   English   中英

Rails通過關聯記錄數進行選擇

[英]Rails select by number of associated records

我的rails應用程序中有以下模型:

class Student < ApplicationRecord
  has_many :tickets, dependent: :destroy
  has_and_belongs_to_many :articles, dependent: :destroy

class Article < ApplicationRecord
  has_and_belongs_to_many :students, dependent: :destroy

class Ticket < ApplicationRecord
  belongs_to :student, touch: true

我需要提取所有少於文章的學生,並且我需要提取所有最后一個票證標題為“ Something”的學生。

到目前為止,我嘗試的所有操作都需要花費大量時間。 我嘗試過映射和遍歷所有學生。 但是我想我需要的是一個聯合請求。 我正在尋找最有效的方法,因為我正在使用的數據庫很大。

您問"I need to extract all Students who has less than articles" 我假設您是說"I need to extract all Students who have less than X articles" 在這種情況下,您需要grouphaving https://guides.rubyonrails.org/active_record_querying.html#group

例如, Article.group(:student_id).having('count(articles.id) > X').pluck(:student_id)

要解決第二個問題,您可以使用急切加載https://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations來加快代碼的速度。

result = students.filter do |student|
  students.tickets.last.name == 'Something'
end

對於第一個問題,請使用@MCI的答案。 但是,通過學生記錄進行filter / select / find_all或其他任何操作(盡管我還沒有聽說過ruby中的過濾方法)需要進行n次查詢,其中n是學生記錄的數量(稱為n + 1查詢)。

studs = Student.find_by_sql(%{select tmp.id from (
  select student_id as id from tickets where name='Something' order by tickets.created_at desc
) tmp group by tmp.id})

這里的關聯是HABTM,因此下面的查詢應該有效

x = 10
Student.joins(:articles).group("articles_students.student_id").having("count(articles.id) < ?",x)

暫無
暫無

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

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