简体   繁体   中英

Query array of objects in Sequelize

How can I query this data with name, what should I write in where clause?

{a: [{name: 'test'}, {name: 'test2'}]}

The example bellow is for first element only. I would like to have for every index.

a: {
       0: {
            name: value
        },
 },

Query by name using pure SQL.

await sequelize.query(
  SELECT
   *
  FROM 
    table_name
  WHERE
     a->>'name' = 'something';
  );

Converting this to sequelize functions should be something equivalent to this query.

Model.findAll<Model>({
  where: { 'a': { name: 'something' } }
});

EDIT AFTER THE COMMENT :

I couldn't find sequelize function for jsonb_array_elements, so I hope a pure SQL query can help.

await sequelize.query(
SELECT * FROM table_name, jsonb_array_elements(table_name.jsonb_column_name) with ordinality arr(item_object)
WHERE item_object->>'name' = 'test';
)

// jsonb_column_name is the same as a 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM