所以我有一个菜单表,id,title,parent_id
我已经在最底层的菜单上附加了一些内容字段(比如id=50),如果我点击树菜单的顶部父菜单(id=1),我希望它显示附加到子菜单的内容(不管有多深),所以我想我需要循环浏览父菜单,你能帮我了解一下这个逻辑吗?
控制器:
$data['query'] = $this->item_model->getByType($menu_id);
型号:
function getByType($menu_id) {
if($menu_id) {
$q = $this->db->get_where('menus', array('id' => $menu_id));
$parent_id = $q->row()->parent_id;
}else{
return;
}
$this->db->select('*');
$this->db->from('items');
$this->db->where('menu_id', $menu_id);
$this->db->or_where('menu_id', $parent_id);
$query = $this->db->get();
return $query;
}
所以到目前为止,如果我点击他的父母(2级),我只会得到一些菜单上的项目,但如何使其深度达到无限级?,我想我需要把or_where
放在一个循环中,你能帮我吗?
Hmz。。。递归!
function getChildrenAttachments($menu_id) {
// invalid menu id
if(!$menu_id) return;
// get all rows with this parent id
$query = $this->db->get_where('menus', array('parent_id' => $menu_id));
// result will hold all the attachments
$result = array();
// loop through results
foreach($query->result() as $row) {
// does this row have an attachment?
if($row->attachment!='') {
$result[] = $row->attachment;
}
// add all children attachments
$result = array_merge($result, getChildrenAttachments($row->id));
}
// return result set
return $result
}
该实现不考虑实际具有附件的当前menu_id
。您可以创建一个新函数,将getAttachmentsForTree()
考虑在内,该函数检查当前id,然后将id传递给getChildrenAttachments()
。。。
附言:我还没有运行代码,所以我对代码可能出现的任何问题感到抱歉。这只是一个例子,说明如何在这种情况下使用递归来获得优势。