Nested JSON of 3 one-to-many tables

I am creating a Sencha-Touch 2 application, and I have some problems with recovering my data from the server side (mysql DB).

Here is my data model:

Table1 : ID:int description:varchar(100) Table2 : ID:int description:varchar(100) table1_ID:int Table3 : ID:int name:varchar(100) info:varchar(100) table2_ID:int 

Table 1 is connected to table 2 with a one-to-many relationship, and also between table 2 and table 3.

What I want from the server is a nested JSON that looks like this:

 [ Table1_object1_ID: 'id' : { Table1_object1_description: 'description', Table2_Objects : [ 'Table2_object1': { Table2_object1_id : 'id', Table2_object1_description : 'description' Table3_Objects : [ table3_object1: { Table3_object1_name : 'name', Table3_object1_info : 'info', }, table3_object2: { Table3_object2_name : 'name', Table3_object2_info : 'info', }, table3_object3: { Table3_object3_name : 'name', Table3_object3_info : 'info', }, etc... ], }, 'Table2_object2': { Table2_object2_id : 'id', Table2_object2_description : 'description' Table3_Objects : [ ... ] }, etc.... ] }, Table1_object2_ID: 'id' : { etc.... ] 

In my application, I use 3 Models for each table, and ideally I want to save my data in 3 stores, but this will be a different problem; -)

The first store (based on the model from Table1 ) executes a JsonP request to get the embedded JSON.

Actually my SQL query in a PHP file is simple:

 SELECT * FROM Table1 INNER JOIN Table2 ON Table1.ID = Table2.table1_ID INNER JOIN Table3 ON Table2.ID = Table3.table2_ID; 

I tried to create an array in PHP from my SQL results, but could not get the wait result. I am also trying to change my SQL using GROUP BY and GROUP_CONCAT , but here, I cannot get JSON.

Some help would be really appreciated.

+4
source share
1 answer

Runnable code with some sample data: http://codepad.org/2Xsbdu23

I used 3 different SELECT to avoid unnecessary repetitions. Of course, you need to tune the $result array to your desired JSON format, but I think it's not that difficult.

 // assume $t1/2/3 will be arrays of objects $t1 = SELECT Table1.* FROM Table1 WHERE Table1.ID = 111 $t2 = SELECT Table2.* FROM Table2 WHERE Table2.table1_ID = 111 $t3 = SELECT Table3.* FROM Table2 INNER JOIN Table3 ON Table2.ID = Table3.table2_ID WHERE Table2.table1_ID = 111 function array_group_by( $array, $id ){ $groups = array(); foreach( $array as $row ) $groups[ $row -> $id ][] = $row; return $groups; } // group rows from table2/table3 by their parent IDs $p2 = array_group_by( $t2, 'table1_ID' ); $p3 = array_group_by( $t3, 'table2_ID' ); // let combine results: $result = array(); foreach( $t1 as $row1 ){ $row1 -> Table2_Objects = isset( $p2[ $row1 -> ID ]) ? $p2[ $row1 -> ID ] : array(); foreach( $row1 -> Table2_Objects as $row2 ) $row2 -> Table3_Objects = isset( $p3[ $row2 -> ID ]) ? $p3[ $row2 -> ID ] : array(); $result[] = $row1; } echo json_encode( $result ); 
+1
source

All Articles