ubergeekzone
4/10/2016 - 11:25 PM

Custom Many-To-Many MySQL Flow

Custom Many-To-Many MySQL Flow

 <?php 
 $flow = array(
            "api_endpoint" => $this->get('from'),
            "index" => $this->get("index"), // leave blank for an all query
            "where" => array("pointer" => "id",
                "table" => "events",
                "type" => "MANY_TO_ONE")
        );
        
        if($flow['where']['type'] == "MANY_TO_ONE") {

            if($flow['api_endpoint'] == $flow['where']['table']) {
                $message = array("status" => 200, "data" => array("message" => $flow['where']['type']." not supported bidirectional please use ONE-TO-MANY"));
                echo $this->response($message, REST_Controller::HTTP_OK);
            }



            $where = '';

            if($flow['index']) {
                $where = " WHERE " .$flow['where']['pointer']. " = '".$flow['index']."'";
            }

            $endpoint = $this->db->query("SELECT * FROM ". $flow['api_endpoint'] . $where);

            if(!$endpoint) {
                $message = array("status" => 200, "data" => array("message" => $flow['api_endpoint'] . " is not a valid endpoint."));
                echo $this->response($message, REST_Controller::HTTP_OK);
            }


            if(empty($endpoint->result_array())) {

                if($flow['index'] == "") {
                    $message = array("status" => 200, "data" => array("message" => "no data found"));

                } else {
                    $message = array("status" => 200, "data" => array("message" => "no data found at index " . $flow['index'] . " for pointer " . $flow['where']['pointer']));

                }
                echo $this->response($message, REST_Controller::HTTP_OK);
            }

            $i = 0;
            foreach ($endpoint->result_array() as $row) {

                $link_one = $this->db->query('SELECT * FROM ' . $flow['where']['table'] . " WHERE id" . " = " . $row[$flow['where']['table']."_id"] . "  ORDER BY id DESC");

                if ($link_one) {
                    //$message = "No link was found between ".$flow['api_endpoint'] . "_" . $flow['where']['table'];
                } else {
                    $message = array("status" => 200, "data" => array("message" => "No link was found between ".$flow['where']['table']));
                    echo $this->response($message, REST_Controller::HTTP_OK);
                }


                $data[] = $row;

                $link_i = 0;
                foreach($link_one->result_array() as $link_one_row) {

                    $data[][$flow['where']['table']][] = $link_one_row;

                    $link_i++;

                }

            }

        }