Skip to content
Advertisement

Fetching constraints in SQL database to JSON in PHP

Let’s assume I have the following database structure of car manufacturers and the corresponding cars:

manufacturers:

cars:

The id column of manufacturers is the primary key and the manufacturer column of cars has the corresponding foreign key constraint.

I’d like to produce the following JSON output using PHPs json_encode:

To get the manufacturers and their founded_in I’d just perform:

And fetch them to an array. How do I assign the cars correctly though, after making a second query?

Advertisement

Answer

If you are using MySQL 5.7 or higher, you can use the JSON aggregate functions to generate the output you expect directly from a SQL query. I expect that will be more efficient than using php in between.

To start with, consider the following aggregates query, that JOINs both tables and creates a JSON object for each manufacturer, with the list of associated car names in a subarray:

This returns:

To produce the expected output, we can turn this to a subquery and add another level of aggregation:

This yields:

Demo on DB Fiddle.

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