mysql - Loopback 4:如何查询对象数组
问题描述
我一直无法根据对象数组中的属性查询对象。
我正在尝试查询所有具有 id 7 事件的订单:
const orders = await this.orderRepository.find({where: {events: {elemMatch: {'id': event.id}}}});
以上给了我以下错误:
ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''{\"id\":\"7\"}
如果我尝试以下过滤器,我总是会得到一个空数组:
{where: {events: {like: '%id%'}}}
Loopback 4 的正确方法是什么?
更新:
我正在使用 MySQL 8.0。
这是我的订单模型中事件的定义:
@property({
type: 'array',
itemType: 'object',
required: false,
})
events: CartItem[] | null;
解决方案
解决方案
由于您使用MySQL
环回连接器连接到MySQL
数据库,因此当前此连接器将两者都String/JSON
视为VARCHAR
. 因此,您可以尝试以下修改来喜欢
{where: {events: {like: '%id:'+7+'%'}}}
或者
const orders = await this.orderRepository.find({
where: {
events: {
like: '%id:'+event.id+'%'
}
}
});
或使用正则表达式
const orders = await this.orderRepository.find({
where: {
events: {
regexp: '.*id:'+event.id+'.*'
}
}
});
const orders = await this.orderRepository.find({
where: {
events: {
regexp: new RegExp(".*id:"+event.id+".*")
}
}
});
试图匹配json
模式{
id:7,name:'Event 7'}
在这种情况下,里面的值id
可能是7
.
假设
根据您的问题和显示的 mysql 错误,做出以下假设:
架构(MySQL v5.7)
create table samples(id int primary key auto_increment, events varchar(400));
insert into samples(events) values
('[{id:3,name:\"Boscobel\"},{id:4,name:\"Rays\"}]'),
('[{id:7,name:\"Boscobel 7\"},{id:8,name:\"Rays 8\"}]');
应该收到结果
查询 #1
select * from samples where events like '%id\:7%';
| id | events |
| --- | ----------------------------------------------- |
| 2 | [{id:7,name:"Boscobel 7"},{id:8,name:"Rays 8"}] |
查询 #2
select * from samples where events like '%id:7%';
| id | events |
| --- | ----------------------------------------------- |
| 2 | [{id:7,name:"Boscobel 7"},{id:8,name:"Rays 8"}] |
不应收到结果
查询 #3
select * from samples where events like '%id\:70%';
没有要显示的结果。
查询 #4
select * from samples where events like '%id:200%';
没有要显示的结果。
推荐阅读
- csv - 如何将 .csv 文件过滤到 GO 上的列中
- python - Discord Bot,如何修复 UnboundLocalError:分配前引用的局部变量“embed_2”?
- flutter - 颤振指南针示例
- android - 如何在buildTypes gradle Android中获取versionName
- sql - 将关联数据分配给变量而不是一次又一次地调用关联是一种好方法吗
- reactjs - React Context 不更新值以传递到另一个页面
- php - 在 WooCommerce 中小计大于 0 时隐藏免费送货
- styles - 如何修改 docsify prismjs 代码块的字体大小?
- discord - Discord JS 成员数
- javascript - 如何在 Nodejs 中为 DynamoDB PartiQL 指定参数