【问题标题】:Wth rails 6 and postgresql, return a object collection using an array item as references使用 rails 6 和 postgresql,使用数组项作为引用返回对象集合
【发布时间】:2021-03-08 16:34:07
【问题描述】:

使用 Rail 6 和 postgres,我需要生成一个对象集合,使用字段 relations 上的项目数组,返回所有与他的关系“重复”的人。

通过此迁移创建的数据库字段:

t.integer :relations, array: true, null: false, default: []
...
add_index :people, :relations, using: :gin

它创建了这个表:

id | name |  relations  |
------------------------|
 1 | João | {nil,1,2,3} |
 2 | Maria| {nil,1}     |

我需要这样的回报,没有 nil;

[
  {id: 1, name: 'João', relation: 1},
  {id: 1, name: 'João', relation: 2},
  {id: 1, name: 'João', relation: 3},
  {id: 2, name: 'Maria', relation: 1}
]

类似那种糟糕的sql:

SELECT id, name, '1' as relation FROM people WHERE 1 = ANY (relations)
union
SELECT id, name, '2' as relation FROM people WHERE 2 = ANY (relations)
union
SELECT id, name, '3' as relation FROM people WHERE 3 = ANY (relations);

tks :)

【问题讨论】:

    标签: arrays ruby-on-rails ruby postgresql


    【解决方案1】:

    这应该会给你预期的结果:

    Person.joins(", unnest(people.relations) rel")
          .where("rel is not null")
          .select("people.id, people.name, rel")
    

    (对于 Postgres 版本 > 9.4)

    【讨论】:

      猜你喜欢
      • 2021-04-24
      • 2020-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-02
      • 2020-01-05
      • 2010-11-05
      • 2018-01-10
      相关资源
      最近更新 更多