M
M
mergenich2014-05-19 21:33:41
MySQL
mergenich, 2014-05-19 21:33:41

How to query three tables and return json?

There are three tables: users, playlists, tracks. Playlists can be shared, and one track can be in different playlists. I'm trying to return user information and playlists with tracks in one json.
First, I made such a database structure with two pivot tables:
a8e7a2997b334669a805c14303163db5.PNG
However, I could not formulate a normal query so that both the user's playlists and the tracks to them would be displayed with one query. There was an idea to take the user's playlists and make separate requests for tracks in a loop, but it seemed to me that it smelled like shitcode and this idea was discarded.
Then I remade the database into this:
2fe3108a5a63479d9bf5f0dcfe1bfb7c.PNG
It works, but json is flat single-level, but I want it with nested objects.
The first variant of the database seems to be good until I returned it back.
We need advice on how to correctly formulate a request for it, and any other decisions are made.
DBMS - MySQL, Laravel PHP, Eloquent ORM.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nazar Mokrinsky, 2014-05-19
@nazarpc

Which array you pass to json_encode() - you will get such JSON. If you don't want a flat one, pass the nested one, it doesn't care.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question