如何使用 sequelize 为包含的 table 的 jsonb 列应用 where 子句?

how to apply where clause for included table's jsonb column using sequelize?

我在 postgres 数据库中有 2 个 table。

Table_A
--------
id BIGINT
metadata JSONB

Table_B
--------
id BIGINT
a_id BIGINT
metadata JSONB

数据

Table_A
id | metadata
1  | {'gender': 'Male', 'name': 'xyz'}

Table_B
id | a_id | metadata
1  | 1    | {'country': 'IN', 'address': 'Banglore'}
2  | 1    | {'country': 'US', 'address': 'New York'}
3  | 1    | {'country': 'IN', 'address': 'Hydrabad'}

我正在使用 sequelize 并尝试应用包含 table 的 jsonb 列的 where 子句。

示例:

let query = {
        where: {
            '$table_b.metadata.address$': 'Banglore'
        }
        include: [
            {
                model: Table_B,
                as: 'table_b'
            }
        ]
    };
    
Table_A.findAndCountAll(query).then((result)=>{
    console.log(JSON.stringify(result.rows));
}).catch((err)=>{
    console.log(err)
})

但是我遇到了以下错误

original: error: missing FROM-clause entry for table "table_b->metadata"
  at Parser.parseErrorMessage (C:\Project\test\FilterTest\node_modules\pg-protocol\dist\parser.js:287:98)
  at Parser.handlePacket (C:\Project\test\FilterTest\node_modules\pg-protocol\dist\parser.js:126:29)
  at Parser.parse (C:\Project\test\FilterTest\node_modules\pg-protocol\dist\parser.js:39:38)
  at Socket.<anonymous> (C:\Project\test\FilterTest\node_modules\pg-protocol\dist\index.js:11:42)
  at Socket.emit (events.js:400:28)
  at addChunk (internal/streams/readable.js:293:12)
  at readableAddChunk (internal/streams/readable.js:267:9)
  at Socket.Readable.push (internal/streams/readable.js:206:10)
  at TCP.onStreamRead (internal/stream_base_commons.js:188:23) {

任何人都可以帮助如何为包含的 table 的 jsonb 列应用 where 子句?

试试这个方法。

const query = {
    include: [{
        model: Table_B,
        as: 'table_b',
        where: {
            metadata: {
                address: 'Banglore'
            }
        }
    }]
};

这应该适用于匹配 JSONB 字段中的属性子集。

============================================= =

更新:

如果您想在顶层应用 where,请使用 JSON.stringify 包装并使用 Op.contains 对属性子集进行部分匹配。

const query = {
    where: {
        '$table_b.metadata$': {
             [Op.contains]: JSON.stringify({
                 address: 'Banglore'
             }
        })
    },
    include: [{
        model: Table_B,
        as: 'table_b'
    }]
};