MySQLi查询使用纯关系表连接多个表

时间:2015-06-11 18:35:14

标签: php mysql database database-design mysqli

所以我有这个架构,如image

所示

现在,虽然我一直想弄清楚如何做到这一点,但我得说我没有变得有点聪明......

我想知道的是,是否可以从一个查询中获得这样的结果?

    {
      "activitys": [
        {
          "activity_name": "Bicycling",
          "attributes": [
            {
              "attribute_name": "Time"
            },
            {
              "attribute_name": "city",
              "options": [
                {
                  "option_name": "Stockholm"
                },
                {
                  "option_name": "Vasteras"
                }
              ]
            }
          ]
        },
        {
          "activity_name":"asdf"
          ...and so on
        }
      ]
    }

如果是这样,我该怎么办?

此外,我的架构看起来很愚蠢还是有一些逻辑呢? 我现在还是新手,我觉得我可能有过于复杂或误解的东西......

先谢谢

编辑:经过多次填充后,我现在设法获取彼此相关的数据,如下所示:

    {
        "success": 1,
        "activitys": [
            {
                "activity_id": "16",
                "activity_name": "Bicycling",
                "attribute_id": "47",
                "attribute_name": "City",
                "option_id": "50",
                "option_name": "Stockholm"
            },
            {
                "activity_id": "16",
                "activity_name": "Bicycling",
                "attribute_id": "47",
                "attribute_name": "City",
                "option_id": "51",
                "option_name": "Vasteras"
            },
            {
                "activity_id": "16",
                "activity_name": "Bicycling",
                "attribute_id": null,
                "attribute_name": "Duration",
                "option_id": null,
                "option_name": null
            },
            {
                "activity_id": "16",
                "activity_name": "Bicycling",
                "attribute_id": "49",
                "attribute_name": "Bike",
                "option_id": "52",
                "option_name": "Grandmas old bike"
            },
            {
                "activity_id": "16",
                "activity_name": "Bicycling",
                "attribute_id": "49",
                "attribute_name": "Bike",
                "option_id": "53",
                "option_name": "My superfast bike"
            },
            {
                "activity_id": "16",
                "activity_name": "Bicycling",
                "attribute_id": "49",
                "attribute_name": "Bike",
                "option_id": "54",
                "option_name": "My childhood bike"
            },
            {
                "activity_id": "16",
                "activity_name": "Bicycling",
                "attribute_id": "49",
                "attribute_name": "Bike",
                "option_id": "55",
                "option_name": "Pablos bike"
            },
            {
                "activity_id": "16",
                "activity_name": "Bicycling",
                "attribute_id": null,
                "attribute_name": "Distance",
                "option_id": null,
                "option_name": null
            },
            {
                "activity_id": "17",
                "activity_name": "Running",
                "attribute_id": null,
                "attribute_name": "Duration",
                "option_id": null,
                "option_name": null
            }
        ]
    }

但是正如您所看到的,由于某种原因,那些没有任何选项的属性的attribute_id没有出现.. 我想当我对其进行排序时,我只需要提出一些算法来按预期格式化我的响应(作为我原始帖子中的JSON字符串),因为使用mysqli返回的行似乎无法实现。

这是我的代码

    if (isset($_POST['get_activitys'])) {
        $records = array();

        $sql = "SELECT * 
                FROM activities a 
                LEFT JOIN activity_attributes aa ON a.activity_id = aa.activity_id 
                LEFT JOIN attributes at ON aa.attribute_id = at.attribute_id 
                LEFT JOIN attributes_options ao ON at.attribute_id = ao.attribute_id 
                LEFT JOIN options o ON ao.option_id = o.option_id";

        if($results = $conn->query($sql)) {
            if ($results->num_rows) {
                while ($row = $results->fetch_object()) {
                    $records[] = $row;
                }
                $results->free();

                if (!count($records)) {
                $response['success'] = 0;
                $response['message'] = "Hittade inga aktiviteter";
                die(json_encode($response));

                } else {
                    $response['success'] = 1;
                    $response['activitys'] = array();

                    foreach ($records as $r) {
                        array_push($response['activitys'], $r);
                    }
                    // Testing
                    echo "<pre>";
                    echo json_encode($response, JSON_PRETTY_PRINT);
                    echo "</pre>";
                    die();

                    die(json_encode($response));
                }           
            } else {
                $response['success'] = 0;
                $response['message'] = "Hittade inga aktiviteter";
                die(json_encode($response));
            }
        } else {
            $response['success'] = 0;
            $response['message'] = "Database query failed: (" . $conn->errno . ") " . $conn->error;
            die(json_encode($response));
        }
    }

1 个答案:

答案 0 :(得分:0)

您的查询没问题。您需要在嵌套数组中构造查询结果。这是未经测试的代码。

if (isset($_POST['get_activitys'])) {
    $records = array();
    $activity_names = array();
    $attribute_names = array();

    $sql = "SELECT * 
            FROM activities a 
            LEFT JOIN activity_attributes aa ON a.activity_id = aa.activity_id 
            LEFT JOIN attributes at ON aa.attribute_id = at.attribute_id 
            LEFT JOIN attributes_options ao ON at.attribute_id = ao.attribute_id 
            LEFT JOIN options o ON ao.option_id = o.option_id";

    if($results = $conn->query($sql)) {
        if ($results->num_rows) {
            while ($row = $results->fetch_object()) {
                $activity_names[$row->activity_id] = $row->activity_name;
                $attribute_names[$row->attribute_id] = $row->attribute_name;
                $records[$row->activity_id][$row->attribute_id][$row->option_id] = $row->option_name;
            }
            $results->free();

            if (!count($records)) {
            $response['success'] = 0;
            $response['message'] = "Hittade inga aktiviteter";
            die(json_encode($response));

            } else {
                $response['success'] = 1;
                $response['activitys'] = array();

                foreach ($records as $activity_id => $activity) {
                    $activity_obj = array('activity_name' => $activity_names[$activity_id], 'attributes' => array());

                    foreach ($activity as $attribute_id => $attributes) {
                        $attribute_obj = array('attribute_name' => attribute_names[$attribute_id], 'options' => array());

                        foreach ($attributes as $option_id => $option_name) {
                            $option_obj = array('option_name' => $option_name);
                            $attribute_obj['options'][] = $option_obj;
                        }

                        if (!count($attribute_obj['options'])) {
                            unset($attribute_obj['options']);
                        }

                        $activity_obj['attributes'][] = $attribute_obj;
                    }

                    if (!count($activity_obj['attributes'])) {
                        unset($activity_obj['attributes']);
                    }

                    $response['activitys'][] = $activity_obj;
                }
                // Testing
                echo "<pre>";
                echo json_encode($response, JSON_PRETTY_PRINT);
                echo "</pre>";
                die();

                die(json_encode($response));
            }           
        } else {
            $response['success'] = 0;
            $response['message'] = "Hittade inga aktiviteter";
            die(json_encode($response));
        }
    } else {
        $response['success'] = 0;
        $response['message'] = "Database query failed: (" . $conn->errno . ") " . $conn->error;
        die(json_encode($response));
    }
}