ruby-on-rails - Rails 使用连接检索重复的列
问题描述
我的协会
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]]
推荐阅读
- active-directory - Gitlab 身份验证返回无效的用户名或密码(缺少 LDAP 窗格)
- flutter - 颤振图像未显示
- python - 如何在这个游戏中改变房间(街机 Python)
- python - 如何在 Tkinter 中动态更新列表框条目?
- pointers - 如何在类中传递指针成员
- python - 由于 Windows 运行时中的错误,当前的 Numpy 安装未能通过健全性检查
- r - 在没有特定格式的文本中查找代码
- c++ - 如何将 int 类型的数字/字母转换为 char 和 *char?
- javascript - 如何创建集成测试中型、第 3 方 API 重型 nodejs 应用程序?
- python - django 如何真正处理开发服务器上的多个请求?