PHP and MySQL - efficiently handling multiple one to many relationships

♀尐吖头ヾ 提交于 2019-12-03 20:51:13

If you really want every piece of data, you're going to be retrieving the same number of rows, no matter how you do it. Best to get it all in one query.

SELECT schedule.id, overrides.id, locations.id, locations.name
FROM schedule
JOIN overrides ON overrides.schedule_id = schedule.id
JOIN locations ON locations.override_id = overrides.id
ORDER BY schedule.id, overrides.id, locations.id

By ordering the results like this, you can iterate through the result set and move on to the next schedule whenever the scheduleid changes, and the next location when the locationid changes.

Edit: a possible example of how to turn this data into a 3-dimensional array -

$last_schedule = 0;
$last_override = 0;
$schedules = array();

while ($row = mysql_fetch_array($query_result))
{
  $schedule_id = $row[0];
  $override_id = $row[1];
  $location_id = $row[2];
  $location_name = $row[3];
  if ($schedule_id != $last_schedule)
  {
    $schedules[$schedule_id] = array();
  }
  if ($override_id != $last_override)
  {
    $schedules[$schedule_id][$override_id] = array();
  }
  $schedules[$schedule_id][$override_id][$location_id] = $location_name;
  $last_schedule = $schedule_id;
  $last_override = $override_id;
}

Quite primitive, I imagine your code will look different, but hopefully it makes some sense.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!