sql >> Base de Datos >  >> RDS >> Mysql

JSON anidado de 3 tablas de uno a muchos

Código ejecutable con algunos datos de muestra:http://codepad.org/2Xsbdu23

Usé 3 SELECT distintos s para evitar repeticiones innecesarias. Por supuesto, debe personalizar el $result matriz a su formato JSON deseado exacto, pero creo que no es tan difícil.

// 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's 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 );