我一直无法根据对象数组中的属性查询对象。
我正在尝试查询具有 ID 为 7 的事件的所有订单:
const orders = await this.orderRepository.find({where: {events: {elemMatch: {'id': event.id}}}});
Run Code Online (Sandbox Code Playgroud)
以上给了我以下错误:
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\"}
Run Code Online (Sandbox Code Playgroud)
如果我尝试以下过滤器,我总是会得到一个空数组:
{where: {events: {like: '%id%'}}}
Run Code Online (Sandbox Code Playgroud)
Loopback 4 的正确方法是什么?
更新:
我正在使用 MySQL 8.0。
这是我的订单模型中事件的定义:
@property({
type: 'array',
itemType: 'object',
required: false,
})
events: CartItem[] | null;
Run Code Online (Sandbox Code Playgroud)
由于您使用MySQL环回连接器连接到MySQL数据库,因此当前此连接器将两者String/JSON视为VARCHAR. 因此,您可以尝试以下修改来喜欢
{where: {events: {like: '%id:'+7+'%'}}}
Run Code Online (Sandbox Code Playgroud)
或者
const orders = await this.orderRepository.find({
where: {
events: {
like: '%id:'+event.id+'%'
}
}
});
Run Code Online (Sandbox Code Playgroud)
或使用正则表达式
const orders = await this.orderRepository.find({
where: {
events: {
regexp: '.*id:'+event.id+'.*'
}
}
});
Run Code Online (Sandbox Code Playgroud)
const orders = await this.orderRepository.find({
where: {
events: {
regexp: new RegExp(".*id:"+event.id+".*")
}
}
});
Run Code Online (Sandbox Code Playgroud)
尝试匹配json模式{id:7,,name:'Event 7'}在这种情况下,内部的值id可能是7。
根据您的问题和显示的 mysql 错误,做出以下假设:
架构(MySQL v5.7)
create table samples(id int primary key auto_increment, events varchar(400));
Run Code Online (Sandbox Code Playgroud)
insert into samples(events) values
('[{id:3,name:\"Boscobel\"},{id:4,name:\"Rays\"}]'),
('[{id:7,name:\"Boscobel 7\"},{id:8,name:\"Rays 8\"}]');
Run Code Online (Sandbox Code Playgroud)
查询#1
select * from samples where events like '%id\:7%';
Run Code Online (Sandbox Code Playgroud)
| id | events |
| --- | ----------------------------------------------- |
| 2 | [{id:7,name:"Boscobel 7"},{id:8,name:"Rays 8"}] |
Run Code Online (Sandbox Code Playgroud)
查询#2
select * from samples where events like '%id:7%';
Run Code Online (Sandbox Code Playgroud)
| id | events |
| --- | ----------------------------------------------- |
| 2 | [{id:7,name:"Boscobel 7"},{id:8,name:"Rays 8"}] |
Run Code Online (Sandbox Code Playgroud)
查询#3
select * from samples where events like '%id\:70%';
Run Code Online (Sandbox Code Playgroud)
没有可显示的结果。
查询#4
select * from samples where events like '%id:200%';
Run Code Online (Sandbox Code Playgroud)
没有可显示的结果。
| 归档时间: |
|
| 查看次数: |
401 次 |
| 最近记录: |