【问题标题】:find by nested object value in sequelize with postgres用postgres在sequelize中通过嵌套对象值查找
【发布时间】:2020-12-02 17:08:34
【问题描述】:

我试图通过嵌套对象数组中的值来查找,但无法正常工作。

假设我有一个名为Forms 的表,该表有一个名为collaborator 的对象数组。

collaborator: DataTypes.ARRAY(DataTypes.JSONB)

来自此协作者数组的典型 json 对象是:

{
 "id": 4,
 "name": 'John'
}

我正在尝试根据collaborator.name 值查找Form。到目前为止,我尝试了这个(来自各种其他问题和谷歌搜索),但它返回 null

Form.findOne({
    where: {
        'collaborator.name': 'John'
    }
})

我正在阅读本手册的 sequelize 本身,但我认为我做错了: https://sequelize.org/v5/manual/querying.html#json

【问题讨论】:

    标签: node.js postgresql sequelize.js


    【解决方案1】:

    您可以使用sequelize.query 函数执行raw query

    "sequelize": "^5.21.3"postgres:9.6,例如

    import { sequelize } from '../../db';
    import { Model, DataTypes, QueryTypes } from 'sequelize';
    
    class Form extends Model {}
    Form.init(
      {
        id: {
          type: DataTypes.INTEGER,
          autoIncrement: true,
          primaryKey: true,
        },
        collaborator: DataTypes.ARRAY(DataTypes.JSONB),
      },
      { sequelize, tableName: 'forms' },
    );
    
    (async function test() {
      try {
        await sequelize.sync({ force: true });
        // seed
        await Form.bulkCreate([
          { collaborator: [{ id: 1, name: 'teresa' }] },
          { collaborator: [{ id: 2, name: 'teng' }] },
          { collaborator: [{ id: 3, name: 'slideshowp2' }] },
          {
            collaborator: [
              { id: 4, name: 'John' },
              { id: 5, name: 'Tim' },
            ],
          },
        ]);
    
        // test
        const data = await sequelize.query(
          `
            SELECT id, collaborator
            FROM   forms f, jsonb_array_elements(to_jsonb(f.collaborator)) obj
            WHERE  obj->>'name' = 'John';
        `,
          { type: QueryTypes.SELECT },
        );
        console.log(JSON.stringify(data));
      } catch (error) {
        console.log(error);
      } finally {
        await sequelize.close();
      }
    })();
    

    执行结果:

    Executing (default): DROP TABLE IF EXISTS "forms" CASCADE;
    Executing (default): DROP TABLE IF EXISTS "forms" CASCADE;
    Executing (default): CREATE TABLE IF NOT EXISTS "forms" ("id"  SERIAL , "collaborator" JSONB[], PRIMARY KEY ("id"));
    Executing (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'forms' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
    Executing (default): INSERT INTO "forms" ("id","collaborator") VALUES (DEFAULT,ARRAY['{"id":1,"name":"teresa"}']::JSONB[]),(DEFAULT,ARRAY['{"id":2,"name":"teng"}']::JSONB[]),(DEFAULT,ARRAY['{"id":3,"name":"slideshowp2"}']::JSONB[]),(DEFAULT,ARRAY['{"id":4,"name":"John"}','{"id":5,"name":"Tim"}']::JSONB[]) RETURNING *;
    Executing (default): SELECT id, collaborator
            FROM   forms f, jsonb_array_elements(to_jsonb(f.collaborator)) obj
            WHERE  obj->>'name' = 'John';
    [{"id":4,"collaborator":[{"id":4,"name":"John"},{"id":5,"name":"Tim"}]}]
    

    检查数据库:

    node-sequelize-examples=# select * from forms;
     id |                             collaborator                             
    ----+----------------------------------------------------------------------
      1 | {"{\"id\": 1, \"name\": \"teresa\"}"}
      2 | {"{\"id\": 2, \"name\": \"teng\"}"}
      3 | {"{\"id\": 3, \"name\": \"slideshowp2\"}"}
      4 | {"{\"id\": 4, \"name\": \"John\"}","{\"id\": 5, \"name\": \"Tim\"}"}
    (4 rows)
    
    node-sequelize-examples=# \d+ forms
                                                    Table "public.forms"
        Column    |  Type   |                     Modifiers                      | Storage  | Stats target | Description 
    --------------+---------+----------------------------------------------------+----------+--------------+-------------
     id           | integer | not null default nextval('forms_id_seq'::regclass) | plain    |              | 
     collaborator | jsonb[] |                                                    | extended |              | 
    Indexes:
        "forms_pkey" PRIMARY KEY, btree (id)
    

    【讨论】:

      猜你喜欢
      • 2018-01-30
      • 2017-01-28
      • 2020-01-22
      • 2021-02-18
      • 2017-01-09
      • 1970-01-01
      • 2022-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多