gpt4 book ai didi

sql - ActiveRecord 查询,按关联排序,has_many 的最后一个

转载 作者:数据小太阳 更新时间:2023-10-29 07:47:38 25 4
gpt4 key购买 nike

我试图通过最近创建的相关记录(通信)的 created_at 列列出所有用户

到目前为止我所拥有的:

User.includes(:communications).order(
'communications.created_at IS NULL, communications.created_at asc'
)

实际上,desc 如我所料地工作。问题是顺序颠倒了,我尝试顺序 asc。这似乎是因为用户 可以有许多通信,查询返回用户 的列表,顺序是第一个通信创建的顺序,而不是最近的。

我如何修改查询以按 ascdesc 顺序定位最近创建的关联记录?

谢谢你的时间。

最佳答案

问题是您正在尝试按子项的属性对父项进行排序,因此您的解决方案只有在他们的订单方向相同时才有效。

使用它的方法是对 child 的属性使用聚合函数,如下所示:

# ascending
User
.joins('LEFT JOIN communications ON communications.user_id = users.id')
.group('users.id')
.order('MAX(communications.created_at) ASC')

# descending
User
.joins('LEFT JOIN communications ON communications.user_id = users.id')
.group('users.id')
.order('MAX(communications.created_at) DESC')

关于sql - ActiveRecord 查询,按关联排序,has_many 的最后一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34603949/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com