Estou tentando construir um menu dinâmico com submenus que insira links provenientes do banco de dados. Eu escrevi o código abaixo diretamente em minha view para testar e funcionou perfeitamente:
<?php
$this->db->from('categories');
$this->db->where('category_id_parent', 0);
$menu_list = $this->db->get();
foreach ($menu_list->result() as $menu): ?>
<li>
<a href=""><?php echo ucwords($menu->category_title) ?></a>
<?php
$cat_id = $menu->category_id;
$this->db->from('categories');
$this->db->where('category_id_parent', $cat_id);
$submenu_list = $this->db->get();
?>
<ul>
<?php foreach ($submenu_list->result() as $submenu): ?>
<li>
<a href=""><?php echo ucwords($submenu->category_title) ?></a>
</li>
<?php endforeach; ?>
</ul>
</li>
<?php endforeach; ?>
Então resolvi criar o model e o controller e adaptar a nova view.
O model ficou assim:
public function get_menu() {
$query = $this->db->get_where('categories', array('category_id_parent' => 0));
if ($query->num_rows() > 0):
return $query;
endif;
}
public function get_submenu() {
$query = $this->db->get_where('categories', array('category_id_parent' => 0));
foreach ($query->result() as $row):
$cat_id = $row->category_id;
endforeach;
if ($cat_id != FALSE):
$this->db->from('categories');
$this->db->where('category_id_parent', $cat_id);
$query = $this->db->get();
return $query;
else:
return FALSE;
endif;
}
O controller :
public function menu() {
$data['menu_list'] = $this->Menu_model->get_menu();
$data['submenu_list'] = $this->Menu_model->get_submenu();
$this->load->view('frontend/header', $data);
}
A view:
<?php foreach ($menu_list->result() as $menu): ?>
<li>
<a href="#" ><?php echo ucwords($menu->category_title) ?> </a>
<ul>
<?php foreach ($submenu_list->result() as $submenu): ?>
<li>
<a href="#"><?php echo ucwords($submenu->category_title) ?></a>
</li>
<?php endforeach; ?>
</ul>
</li>
<?php endforeach; ?>
Está quase tudo funcionando exceto os submenus que repetem os mesmos links.
Onde eu estou errando?
Eu refiz o método get_submenu apenas para pegar os ids do submenu:
public function get_submenu() {
$query = $this->db->get_where('categories', array('category_id_parent !=' => 0));
if ($query->num_rows() > 0):
return $query;
endif;
}