【问题标题】:How to get a group of attributes associated with another group of attributes?如何获取与另一组属性关联的一组属性?
【发布时间】:2020-08-21 01:32:27
【问题描述】:

这应该很简单,但我很难找到答案。我只想要一组通过外键关联到另一组记录的记录。例如,如果我通过 Song.artist_id 有 Song belongs_to Artist,并且通过 Artist.where(mustache: true) 有一组 Artists,我想要一个返回属于所有这些 Artists 的所有歌曲的查询。所以像:

@songs = Artist.where(mustache: true).songs

但这确实有效。

【问题讨论】:

  • 阅读rails guides on associations 并坐下来用一张纸或一个UML 程序绘制您领域中的对象并规划它们之间的关系。
  • Song.where(artist_id: Artist.where(mustache: true))

标签: sql ruby-on-rails postgresql activerecord arel


【解决方案1】:

Song.where(artist_id: Artist.where(mustache: true).select(:id))

或者

song.joins(:artist).where(artists: {mustache: true})

【讨论】:

  • 在第一个查询中最好使用select而不是pluck,它将只创建一个sql语句而不是两个
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-02-16
  • 1970-01-01
  • 2023-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多