简体   繁体   中英

Increase the depth of an MySQL query

public function get_children($id)
{
        $query = $this->db->query("SELECT 
          @last_id := id AS id,
          parent_id,
          FIO,
          @depth := IF(parent_id = ".$id.", 1, @depth + 1) AS depth,
          @first := IF(id = ".$id.", 'first', null) AS first
          FROM 
          users 
          FORCE INDEX (index_parent_id, PRIMARY, index_both),
          (SELECT @last_id := ".$id.", @depth := -1) vars
          WHERE id = ".$id." OR parent_id = @last_id OR parent_id = ".$id."
          ");

    return $query;

}

How can i increase the level depth of children nodes using the adjacent-model-list and this query, by now it gives me the root parent(selected by id in the function) and their children, but not deeper, any ideas?

foreach($query->result() as $q){


    if($q->first == 'first')
    {
        $parent_id = $q->parent_id;
        break;
    }


}
function print_list($array, $parent=0) {
        print "<ul>";
        foreach ($array as $row) {
            if ($row->parent_id == $parent) {
                print "<li>$row->FIO";
                print_list($array, $row->id);  # recurse
                print "</li>";
        }   }
        print "</ul>";
    }
echo print_list($query->result(), $parent_id);

then I render it in the view file...please help or any advices about what to change or see to increase the depth of the mysql query.

I'm not sure about the schema of the database, but this is basically a stripped down version of something you might be looking for. Basically, you'll need a function that calls itself, but the argument changes.

In this case, it looks for users with parent_id = $parent_id (assuming the parent_id of the root is 0) lists then, and for each of the users, it looks for other users with parent_id = $id (where $id is their id) so basically, you have infinite depth

<?
function print_list($parent_id) {
    $query = "SELECT * FROM users WHERE parent_id=".$parent_id;

    print "<ul>";
    foreach($query->result() as $q) {
        $id = $q->id;
        print "<li>";
            print $q->FIO;
        print "</li>";
        print_list($id); //Here, it calls itself again
    }
    print "</ul>";
}
print_list(0); //Assuming the root-parent-id number is 0

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