Custom Fields, dots and MySQL’s JSON_EXTRACT

We all know custom fields – hopefully – at least this is not about the basics. You can add custom fields to nearly all entites: orders, products, categories, … You can name them whatever you like, e.g. pluginname.property – but using dots . in your custom field name is a bad idea, because then you can’t filter intuitively.

Shopware is using JSON_EXTRACT under the hood which is great, because it offers us native json features. But at the same time we need to know what we are doing, a dot in json/jq is a sign for “subarray”, like this:

{
    "plugin": {
         "property": "Some text"
    }
}

We can access the property by using plugin.property. But because we build the customFields array from a PHP array and not “real” json, we might end up with something like this, when using a dot in our PHP array:

{
    "plugin.property": "Some text"
}

And now we can’t use plugin.property anymore, because it is translated to

JSON_EXTRACT(`order`.`custom_fields`, '$.plugin.property')

and this fails on our json object.

Solution

Know what you are doing! We can use double quotes to fix this and thankfully Shopware pass them to the query:

new EqualsFilter(
    'customFields.plugin.property',
    'our text'
),

// or 

new EqualsFilter(
    'customFields."plugin.property"',
    'our text'
),

Or maybe just don’t use a dot ?

Leave a Reply