使用sequelize查询Postgres嵌套JSONB列

问题描述

嗨,我有一个表,我在其中使用JSONB来存储嵌套的JSON数据,并且需要查询此JSONB列 下面是表格的结构

 {
          "id": "5810f6b3-fefb-4eb1-befc-7df11a24d997","entity": "LocationTypes","event_name": "LocationTypes added","data": {
            "event":{
            "id": "b2805163-78f0-4384-bad6-1df8d35b456d","name": "builidng","company_id": "1dd83f77-fdf1-496d-9e0b-f502788c3a7b","is_address_applicable": true,"is_location_map_applicable": true}
          },"notes": null,"event_time": "2020-11-05T10:56:34.909Z","created_at": "2020-11-05T10:56:34.909Z","updated_at": "2020-11-05T10:56:34.909Z"
        }

下面的代码给出了空白数组作为响应


    const dataJson = await database.activity_logs.findAll({
          where: {
            'data.event.id': {
              $eq: 'b2805163-78f0-4384-bad6-1df8d35b456d',},raw: true,});

有什么方法可以更好地使用sequelize完成对嵌套json对象的查询

解决方法

您应该尝试sequelize.literal并将JSON运算符/函数包装在sequelize.where中。像这样:

sequelize.where(sequelize.literal("data->'event'->'id'"),'=','b2805163-78f0-4384-bad6-1df8d35b456d')