sql - 如何按属性分组但显示嵌套属性的值?
问题描述
我的 Rails 6 应用程序中有这些模型:
class Client < ApplicationRecord
belongs_to :account
has_many :people
end
class Person < ApplicationRecord
belongs_to :client
end
class Payment < ApplicationRecord
belongs_to :client
end
在我SharesController
的尝试中,我试图为每个人生成总付款client
并将它们显示为饼图:
class SharesController < ApplicationController
def index
@clients = current_account.clients.joins(:payments)
.where(:payments => {:date => @range, :currency => @currency})
.order("sum_payments_#{@part} DESC")
.group("clients.id", "clients.name")
.having("sum_payments_#{@part} > 0")
.sum("payments.#{@part}")
end
end
问题在于它client
正确分组。但是,name
我不想显示每个客户的,而是想显示last_name
每个客户的第一个嵌套的person
.
如何才能做到这一点?
谢谢你的帮助。
解决方案
您应该尝试在 and 之间创建一个连接Client
,Person
然后使用它uniq
来避免重复的客户端。
你可以尝试这样的事情(我不确定这段代码是否有效,只是为了更清楚我的意思)
@clients = current_account.clients.joins(:payments, :people)
.where(:payments => {:date => @range, :currency => @currency})
.order("sum_payments_#{@part} DESC")
.group("clients.id", "people.last_name")
.having("sum_payments_#{@part} > 0")
.sum("payments.#{@part}")
推荐阅读
- c++ - Visual Studio Code 在终端中运行程序以进行输入
- php - 如何加入2选择?
- python - 在 Pandas 中跨多种电影类型的 Groupby
- java - 是否可以在类的方法中将@InjectMocks 注入到临时对象实例中?
- sql - POSTGRES - 超级用户无法访问 pg_authid 表
- c# - UI Automation using Selenium c# for Windows App 使用带有 CEF 框架的 WPF 应用程序开发
- django - 工人不运行时执行芹菜任务
- extjs - 创建扩展元素的新实例
- typescript - 将 chart.js x 轴标签格式化为特定时区
- android - strings.xml 中 CHAR_LIMIT 的用途是什么?