在视图中调用模型函数

时间:2014-05-07 11:32:29

标签: codeigniter

我正在尝试访问模型中的函数,在我的codeigniter视图中,它无法正常工作。 有人可以告诉我问题出在哪里。

MODEL:

function gettemplates()
    {
        $sql = "select * from srs_templates";
        $query =  $this->db->query($sql);
        $result = $query->result_array();
        echo "<pre>"; print_r($result);exit;
        return $result;
    }

查看:

<select id="special" >
    <?php echo $this->dashboard_ext_model->gettemplates(); ?>
</select>

2 个答案:

答案 0 :(得分:0)

改变这个:

    echo "<pre>"; print_r($result);exit;

对此:

   echo "<pre>"; print_r($result); echo "</pre>";

基本上删除退出。退出中止脚本。

你永远不应该有充分的理由从视图中调用模型。模型数据应传递给控制器​​,然后传递给视图。

答案 1 :(得分:0)

由于这是MVC(模型视图控制器),因此您不应该从视图中调用模型。 您应该在控制器内部调用Model,然后作为参数传递给视图。

型号:

function gettemplates()
{
    $sql = "select * from srs_templates";
    $query =  $this->db->query($sql);
    $result = $query->result_array();
    echo "<pre>"; print_r($result);exit;
    return $result;
}

控制器:

function gettemplates(){

     //$this->dashboard_ext_model = $this->load->model('dashboard_ext_model'); 
     //uncomment this if you didn't load the model

     $data['templates'] = $this->dashboard_ext_model->gettemplates();

     $this->view->load('page_name', $data);
}

查看:

<select id="special" >
    <?php echo $templates ?>
</select>

MVC最初可能看起来很愚蠢,但它确实对大型项目有帮助。

MVC DESIGN:http://i.stack.imgur.com/Beh3a.png