How to display data from the database using models

2020-05-01 06:26发布

问题:

I am currently creating a new application feature where in I want to dynamically change the values of page headers, page header titles, and breadcrumbs that are fetched from database and not manually code them individually. The thing is, if I update the menu_name column in the database, all page headers, page header titles and breadcrumbs will be automatically be updated based on it's values.

This is the model I created to fetch the values of the columns in the menu_master table

class Page_Header_model extends CI_Model {

public function __construct()
{
    parent::__construct();
}

function get_page_menu_names($menu_id, $menu_name)
{
    $this->db->where('menu_id', $menu_id);
    $this->db->where('menu_name', $menu_name);

    $query = $this->db->get('menu_master);

    return $query->result();
}

Here is the page_header_helper that I want to call the model in order for the values to be displayed automatically

function __construct()
{
   parent::__construct();
   $CI =& get_instance();
   $CI->load->model('Page_Header_model');
   $CI->Page_Header_model->get_page_menu_names();
}

function get_page_header_data($page_type)
{
      $project_title = 'Testing';

      $page_header_array['inventory'] = array(

        "breadcrumbs" =>  array(
            array('title'=>'Home','url'=>base_url()),
            array('title'=>'Inventory Lists','is_active'=>TRUE),
        ),
        "page_title"  =>  'Inventory Lists',
        "page_header_title" =>  'Inventory Lists : '.$project_title

    );

    $page_header_data = $page_header_array[$page_type];

    return $page_header_data;
    }

回答1:

I just figured out a way on how to do this. The key is to get the id of the menu name from the database and return it as a row and in the custom helper, just call the id of the menu name from the database. Here is how I did it:

Here is my model:

        function get_page_menu_names($menu_id)
       {
           $this->db->select('menu_name');

           $this->db->from('menu_master');

           $this->db->where('menu_id', $menu_id);

           $query = $this->db->get();

           $menu_name_row = $query->row();

           if(isset($menu_name_row))
           {
             return $menu_name_row->menu_name;
           }            
       }

And here is how I called it from the helper that I wrote out:

$page_header_array['inventory_master_listing'] = array(

            "breadcrumbs" =>  array(
                array('title'=>'Home','url'=>base_url()),
                array('title'=> $this->my_model_name->get_page_menu_names(1),'is_active'=>TRUE),
            ),
            "page_title"  =>  $this->my_model_name->get_page_menu_names(1),
            "page_header_title" =>  $this->my_model_name->get_page_menu_names(1).' : '.$project_title

        );