[英]Rails using joins retrieve repeated column
我的協會
class Website < ApplicationRecord
has_many :settings
has_one :shop
end
設置和商店表值是:
2.6.1 :003 > Setting.all.pluck(:records)
=> [2, 2, 4, 0, 0, 0]
2.6.1 :003 > Shop.all.pluck(:records)
=> [4, 1, 1]
使用連接
Website.joins(:settings, :shop).where("websites.id = ?", 2).pluck("settings.records", "shops.records")
我得到了重復的價值
[[2, 4], [2, 1], [2, 1], [2, 4], [2, 1], [2, 1], [4, 4], [4, 1], [4, 1], [0, 4], [0, 1], [0, 1], [0, 4], [0, 1], [0, 1], [0, 4], [0, 1], [0, 1]]
我想要的結果
[[2, 4], [2, 1], [4, 1], [0, 0], [0, 0], [0, 0]]
我該如何解決問題?
提前致謝 :)
我不知道你為什么期望結果是[[2, 4], [2, 1], [4, 1], [0, 0], [0, 0], [0, 0]]
(也許是是一個錯字?),但是如果您想從連接查詢中獲得非重復結果,您可以使用group
+ distinct
:
Website.joins(:settings, :shop).where("websites.id = ?", 2).group("settings.records", "shops.records").distinct.pluck("settings.records", "shops.records")
=> [[0, 1], [0, 4], [2, 1], [2, 4], [4, 1], [4, 4]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.