簡體   English   中英

如何在單個查詢中從 ActiveRecord 中的父級 select uniq 子級?

[英]How to select uniq child from parent in ActiveRecord in a single query?

我有一個名為User的模態

class User < ActiveRecord::Base
   has_many: :posts
end

和另一個名為Post的模態

class Post < ActiveRecord::Base
   belongs_to :user
end

如果我有一個范圍內的帖子 object (比如posts = Post.where(id: [1,2,3,4]

如何使用活動記錄方法查詢所有帖子的 uniq 用戶

我知道它可以在兩個查詢中完成,有沒有辦法在一個查詢中完成?

嘗試,如文檔中所示:

User.joins(:posts).where(posts: {id: [1,2,3,4]})

或者,如果您已經有一個名為posts的實例:

User.joins(:posts).where(posts: {id: posts})

通過考慮內部聯接的工作方式,您可以使用一個查詢。 如果您使用User.joins(:posts) ,這將執行內部聯接,並將僅返回至少有 1 個帖子的用戶。 此外,您想過濾這些帖子,您可以使用 ActiveRecord 中的merge方法來實現。 結果將是:

User.joins(:posts).merge(Post.where(id: [1,2,3,4]))

這將創建一個 SQL 查詢

1 個帶有一些 ruby 處理的查詢

Post.eager_load(:user).where(id: [1,2,3,4]).map(&:user)

User.where id: posts.distinct.select(:user_id)

暫無
暫無

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

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