简体   繁体   中英

One to many database relationship to JSON

I use MySQL and PHP (+ PDO_mysql) and my goal is to return some JSON.

I have two database tables, Department and Team.

A department is basically just an id + department name.
A team is basically an id + team name and a foreign key to the corresponding department.

A team can only belong to one department and a department can have many teams (thus the One-to-many relationship).

I would like return some JSON structured this way:

{
    "departments": [
        {
           "departmentname": "Kids",
           "teams": [
              {
                  "teamname": "Black n' white",
                  "homepage": "www.some.thing"
              },
              {
                  "teamname": "Team-1337",
                  "homepage": "www.some.thing"
              }
           ]
        },
        {
           "departmentname": "Kids",
           "teams": [
              {
                  "teamname": "I <3 Sundays",
                  "homepage": "www.some.thing"
              },
              {
                  "teamname": "Stack Overflow",
                  "homepage": "www.some.thing"
              }
           ]
        }
    ]
}

I think I have to make an INNER JOIN between the two tables (department and team) this way:
SELECT * FROM team INNER JOIN department ON team.department_id=department.id

… and in the end of my PHP-file use json_encode , but I have no idea how to get there.

I really appreciate any help you can provide

One way to do it is to perform your join in the PHP code instead of in SQL using associative arrays keyed on the ID columns. Note that the following code is not at all tested, but you get the idea.

$pdo=new PDO("mysql:dbname=database;host=127.0.0.1","user","password");
$statement=$pdo->prepare("SELECT * FROM team WHERE department_id IN (SELECT department.id FROM department)");// get teams in departments
$statement->execute();
$teams=$statement->fetchAll(PDO::FETCH_ASSOC);
$statement=$pdo->prepare("SELECT * FROM department"); // get departments
$statement->execute();
$departments=$statement->fetchAll(PDO::FETCH_ASSOC); // Assumes that department id it the first field

// merge the teams with the departments
foreach($teams as $team){
    $teamDept = $departments[$team["department_id"]];// The department of current team
    // Create an associative list keyed on team id inside the departments
    if(!array_key_exists("teams", $teamDept))// Create team array in department if not exist
        $teamDept["teams"] = array(); // Unsure if I need to do this.
    $teamDept["teams"][$team["id"]] = $team;
}
$json=json_encode($departments);

Another method would be to use the PDO::fetch_group. I did a little research on the subject but was unable to find much examples or detailed tutorial. It does look interesting though.

$pdo=new PDO("mysql:dbname=database;host=127.0.0.1","user","password");
$statement=$pdo->prepare("SELECT * FROM team INNER JOIN department ON team.department_id=department.id");
$statement->execute();
$results=$statement->fetchAll(PDO::FETCH_ASSOC);
$json=json_encode($results);

You mean this?

Use PDO::fetch_group to group records based on the first column.

Here is an example:

$data = $pdo->query('SELECT sex, name, car FROM users')->fetchAll(PDO::FETCH_GROUP);
array (
  'male' => array (
    0 => array (
      'name' => 'John',
      'car' => 'Toyota',
    ),
    1 => array (
      'name' => 'Mike',
      'car' => 'Ford',
    ),
  ),
  'female' => array (
    0 => array (
      'name' => 'Mary',
      'car' => 'Mazda',
    ),
    1 => array (
      'name' => 'Kathy',
      'car' => 'Mazda',
    ),
  ),
)

Example source: https://phpdelusions.net/pdo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM