【问题标题】:Get the first instance of a record based on the value of a column根据列的值获取记录的第一个实例
【发布时间】:2015-06-27 16:29:56
【问题描述】:

我有两个模型,一个是Repository,第二个是Photo。一个存储库可以有许多照片。

我的最终目标是显示一组存储库和每个存储库的显示图片。

我想做类似的事情:

@repositories = Repository.limit(10)
repositories_id = @repositories.map &:id
@photos = Photos.where(repository_id: repositories_id)

但是,这将返回多个具有相同 repository_id 的照片对象,我只想要第一个实例。

【问题讨论】:

  • 在查询结束时使用.first
  • 哪一个?最后?因为那只会给我一个照片对象,而我需要 10 个。
  • 你想要第一个实例......酷。首先基于任何条件或任何随机优先...?
  • 首先基于最低的Photo id。
  • 好的..感谢您提供的信息

标签: ruby-on-rails ruby database model


【解决方案1】:

最简单的方法是将Photo 查找移动到map。这不会是最有效的查询模式,但在 10 个存储库上,它会好一阵子。

@repositories = Repository.limit(10)
@photos = @repositories.map do |repository|
  Photo.where(repository_id: repository.id).first
end

或者如果你设置Repository.has_many :photos

@repositories = Repository.limit(10)
@photos = @repositories.map do |repository|
  repository.photos.first
end

更新 3 个查询而不是 11 个

@repositories = Repository.limit(10)
repository_ids = @repositories.map &:id
photo_ids = Photo.where(repository_id: repository_ids).group(:repository_id).minimum(:id)
photos = Photo.find(photo_ids.values)

【讨论】:

  • 这将从我的数据库中加载 10 个照片对象。个别。我不想为这个查询点击我的 Db 10 次。
  • 添加了更高效的模式。如果您编写完全自定义的using PARTITION or a subquery,我认为您可以在一个查询中完成。
猜你喜欢
  • 1970-01-01
  • 2021-07-13
  • 1970-01-01
  • 2020-01-27
  • 1970-01-01
  • 2021-08-31
  • 2022-11-25
  • 1970-01-01
  • 2014-08-29
相关资源
最近更新 更多