Skip to content
Advertisement

GROUP_CONCAT to return an object array in a many to many relationship

I am working on a mySQL query for a personal project. Right now the end goal is to have the query return the following json for each item:

My most recent attempt is:

Which is giving me an internal server error. Testing it with a simplier query goes through fine so I’ve narrowed it down to the query itself being the issue.

The query below got me close:

It returned objects like this:

But while I get the ids of all the colorsUsed I do not get them in an array, let alone the array of objects I need there. I feel like GROUP_CONCAT isn’t the right solution for this, or at least that I’m not using it correctly, but it’s what comes up when I’ve been trying to find the solution. Just a point in the right direction to keep looking would be helpful too.


My database is structured as so: [db diagram][https://i.stack.imgur.com/lxsvv.png]

Advertisement

Answer

Instead of using string concatenation function such as GROUP_CONCAT(), you can generate a valid JSON object using MySQL JSON functions. JSON_OBJECT() can be used to create objects, and JSON_ARRAYAGG() is an aggregate functions that generates JSON arrays.

First, let’s start with a query that returns all needed columns:

Now we can turn on aggregation an use the JSON functions to generate the expected resultset:

This returns a resultset with a unique column, where each record contains the expected JSON object.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement