I have been unable to query objects based on a property in an array of objects.
I am trying to query all orders that have the event with id 7:
const orders = await this.orderRepository.find({where: {events: {elemMatch: {'id': event.id}}}});
The above gives me the following error:
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\"}
If i try the following filter, I always get an empty array back:
{where: {events: {like: '%id%'}}}
What is the correct approach for Loopback 4?
UPDATE:
I am using MySQL 8.0.
This is the definition of events in my order model:
@property({
type: 'array',
itemType: 'object',
required: false,
})
events: CartItem[] | null;
Solution
Since you are using the
MySQL
loopback connector to connect to yourMySQL
database, currently this connector treats bothString/JSON
asVARCHAR
. As such, you could try the following modification to likeor
or using regular expressions
in an attempt to match the
json
pattern{
id:7,name:'Event 7'}
where in this case the value insideid
could be7
.Assumptions
Based on your question and the mysql error shown, the following assumptions were made:
Schema (MySQL v5.7)
Should Receive Results
Query #1
Query #2
Should Not Receive Results
Query #3
There are no results to be displayed.
Query #4
There are no results to be displayed.
View on DB Fiddle