Bookshelf.js在Postgresql中使用json列的问题

6

我想用查询语句来获取包含 JSON 类型的数据列中的元素。我的表有一个 'data' 数据列,我想要获取在这个数据列中 'team' = 'PSG' 的所有元素。

我的测试代码如下:

  collection.query('whereRaw', "data->'team'->>'PSG'");

我遇到了这个错误:

"WHERE子句的参数必须是布尔类型,而不是文本类型"

或者我测试

collection.query('where', "data", "#>", "'{team, PSG}'");

我遇到了这个错误

"操作符 \"#>\" 不被允许"

我认为这可能是一个与https://github.com/tgriesser/bookshelf/issues/550相关的问题。

1个回答

4

简短回答:

collection.query('where', 'data', '@>', '{"team": "PSG"}');

解释:

假设你有一个名为foos的表格,其中元素foo

 ------------------------
| id | attr              |
 ------------------------
| 0  |{ "bar": "fooBar"} | 
 ------------------------
| 1  |{ "bar": "fooFoo"} | 
 ------------------------

那个的原始查询类似于。
select * from "foos" where "attr" @> '{"bar":"fooBar"}';

现在,在书架中,如果您有一个表示表foos的模型Foo,查询应该如下所示。
Foo.where('attr', '@>', '{"bar":"fooBar"}').fetch().then(function(rows){});

现在针对你的情况,应该是这样的。
collection.query('where', 'data', '@>', '{"team": "PSG"}');

希望Zlatan能够批准它。


我正在使用相同的查询,但仍然出现错误:“Unhandled rejection error: select“foo”。* from“foo”where“attr”@> $1 limit $2 - operator does not exist:json @> unknown”。 - Vasanth
请您在 knex 查询中加入 debug 标志并发布您的确切查询? - Muhammad Raihan Muhaimin
谁想要完成相同的任务,请不要按照这些说明操作。Vasanth在2016年10月19日的评论仍然有效。PostgreSQL会生成以下错误:ERROR: operator does not exist: json @> unknown LINE 1: ...t * from "users" where "email_subscription_prefs" @> '{"mark... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. - tabish89

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接