【问题标题】:Get data after sorting according to indirect mapped data根据间接映射数据排序后获取数据
【发布时间】:2016-03-31 06:00:19
【问题描述】:

PostgreSQL 数据库上考虑以下模型。

class Foo < ActiveRecord::Base
  has_many :bars
end

class Bar < ActiveRecord::Base
  has_many :cars
  belongs_to :foo
end

class Car < ActiveRecord::Base
  has_many :jars
  belongs_to :bar
end

class Jar < ActiveRecord::Base
  belongs_to :car
end

我想要Foo 的列表,按Jar 的数量顺序排列。

例如,考虑一个 Foo 对象数组

[f1, f2, f3] 

每个Foo 对象包含以下数量的Jar 对象

f1 => 1 个 Jar 对象

f2 => 5 个 Jar 对象

f3 => 2 个 Jar 对象

那么想要的顺序是

[f2, f3, f1]

【问题讨论】:

    标签: ruby postgresql ruby-on-rails-4 rails-activerecord


    【解决方案1】:
    Foo.joins(bars: {cars: :jars}).group('foo.id, jars.id').order('COUNT(jars.id)')
    

    Jar 模型上编写 where 子句:

    Foo.joins(bars: {cars: :jars}).where(jars: {name: 'I am jar'})
    

    【讨论】:

    • 它需要少量更正,应该是joins(bars: {cars: :jars}).group('foos.id,jars.id')。如果您可以添加一个为 jar 模型编写 where 子句的解决方案,那就太好了
    • @RohitJangid 编辑并添加了查询jars表的表单
    猜你喜欢
    • 2021-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-27
    • 1970-01-01
    • 1970-01-01
    • 2014-04-21
    相关资源
    最近更新 更多