首页 > 解决方案 > 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;

标签: mysqlloopback4

解决方案


解决方案

由于您使用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%';

没有要显示的结果。


在 DB Fiddle 上查看


推荐阅读