我有两个模型,Device
和HealthRecord
,它们的基本关系是:device has_many health_records
health_records belong_to device
。
我想获得最近创建了health_records的最后10个设备。我可以用这个得到它,但它得到了所有的记录:
Device
.select("devices.id, MAX(health_records.id) AS latest_health_id")
.joins(:health_records)
.group("devices.id")
.order("latest_health_id DESC")
如果我加上.limit(10)
,它只会给我一个我无法检查的Device::ActiveRecord_Relation
。(当我检查时,它显示无效列名"latest_health_id"。(。添加.first(10)
也不起作用。
根据下面分享的描述,查询将获取最近10个创建的健康记录的设备。
Device
.select("devices.id")
.joins(:health_records)
.group("devices.id")
.order("health_records.created_at DESC").limit(10)
我认为您可以通过以下查询实现您的目标:
Device
.joins(:health_records)
.order('health_records.created_at DESC')
.group(:id)
.distinct
.limit(10)
这将返回Device::ActiveRecord_Relation
对象。如果您只想要id,只需在末尾添加pluck(:id)
,这将把您的查询从SELECT DISTINCT "devices".*
更改为SELECT DISTINCT "devices"."id"
,并返回id的Array
。
这里有另一个可能适合您的解决方案(尽管未经测试(:
Device.where(id: HealthRecord.select(:device_id)
.group(:device_id)
.order("MAX(health_records.id) DESC")
.limit(10)
)
这将导致类似的查询
SELECT
devices.*
FROM
devices
WHERE
id IN (
SELECT
health_records.device_id
FROM
health_records
GROUP BY
health_records.device_id
ORDER BY
MAX(health_records.id) DESC
LIMIT 10 OFFSET 0
)
目前,我最终使用了这两个选项中的任何一个:
Device
.select("devices.id, MAX(health_records.id) AS latest_health_id")
.joins(:health_records)
.group("devices.id")
.order("latest_health_id DESC")
.map(&:id).first(10)
Device
.joins(:health_records)
.order('health_records.created_at DESC')
.pluck(:id).uniq.first(10)
它给了我一个最近创建了health_record 的最后10个设备ID的数组