2

MySQL からメニュー項目を引き出したい。

Main menu           id=1, parentid=0
-Contact us         id=2, parentid=1
-Music              id=3, parentid=1
 --Rock             id=8, parentid=3
 --Classic          id=9, parentid=3
-Car                id=4, parentid=1
  --Toyota          id=5, parentid=4,
  --Ford            id=6, parentid=4,
  --Honda           id=7, parentid=4

Other menu          id=10, parentid=0
-Othermain          id=11, parentid=10
  --submenu         id=12, parentid=11

etc.

id=1 から 4 までのデータを引き出して、「...where parentid=1」などで表示できます。しかし、これはトップ レベルのみを引き出します。

しかし、各メニュー(メインメニュー)のサブメニューも含めてすべてのデータを引き出したいです。

このために MySQL でクエリを作成する方法を教えてください。

前もって感謝します。

4

2 に答える 2

4

すべての子を取得するためにデータベースを繰り返し呼び出すには、再帰を実装する必要があります。私のデータベース抽象化レイヤーの実装を独自のものに置き換える必要がありますが、概念は同じです。

memcacheソリューション

function generateTree($parentid = 0, &$tree) {
    $sql = sprintf('SELECT * FROM navigation WHERE parentid = %d', $parentid);
    $res = $this->db->results($sql);
    if ($res) {
        foreach ($res as $r) {
            // push found result onto existing tree
            $tree[$r->id] = $r;
            // create placeholder for children
            $tree[$r->id]['children'] = array();
            // find any children of currently found child
            $tree = generateTree($r->id, $tree[$r->id]['children']);
        }
    }
}

function getTree($parentid) {
    // memcache implementation
    $memcache = new Memcache();
    $memcache->connect('localhost', 11211) or die ("Could not connect"); 
    $tree = $memcache->get('navigation' . $parentid);
    if ($tree == null) {
        // need to query for tree
        $tree = array();
        generateTree($parentid, $tree);

        // store in memcache for an hour
        $memcache->set('navigation' . $parentid, $result, 0, 3600);
    }
    return $tree;
}

// get tree with parentid = 0
getTree(0);

非memcacheソリューション

function generateTree($parentid = 0, &$tree) {
    $sql = sprintf('SELECT * FROM navigation WHERE parentid = %d', $parentid);
    $res = $this->db->results($sql);
    if ($res) {
        foreach ($res as $r) {
            // push found result onto existing tree
            $tree[$r->id] = $r;
            // create placeholder for children
            $tree[$r->id]['children'] = array();
            // find any children of currently found child
            $tree = generateTree($r->id, $tree[$r->id]['children']);
        }
    }
}

// get tree with parentid = 0
$tree = array();
$parentid = 0;
generateTree($parentid, $tree);

// output the results of your tree
var_dump($tree); die;

上記はテストされていないので、誰かがエラーを見つけた場合は、私に知らせてください。または、遠慮なく更新してください。

于 2009-12-07T12:44:41.817 に答える
1

最速の方法は、テーブルからすべての要素をフェッチし、コード側でメニュー ツリーを構築することです。

于 2009-12-07T12:24:37.440 に答える