【问题标题】:How to access Model from Views in CodeIgniter如何从 CodeIgniter 中的视图访问模型
【发布时间】:2017-07-14 08:32:09
【问题描述】:

如何从 Codeigniter 中的视图访问模型。

我有一个带有函数的模型,我需要从视图中调用这个函数

【问题讨论】:

标签: codeigniter view model


【解决方案1】:

请先阅读 CI 文档:

如果您使用的是MVC 结构化框架,那么您应该遵循它的工作方式。

你需要控制器:

public function your_controller_function(){

    // To load model
    $this->load->model ('your_model');

    //To Call model function form controller
    $data = $this->your_model->model_function($ex_data);

    //TO Send data to view
    $this->load->view('your_view',['data'=>$data]);
}

在您的模型内部:

public function model_function($ex_data){
    // Your Querys
    // user return to send you query result to the controller anything
   // Sample Example of query and return

    $query = $this->db->select('*')     
    ->where('your_column',$data['column_name'])
    ->get('your_table');

    $your_result = $query->row_array();

    if($this->db->affected_rows() > 0){
         return your_result;

     } else {

        return FALSE;
     }
}

【讨论】:

    【解决方案2】:

    在你的视图中你可以写:

    <?php
    $this->load->model('your_model');
    $this->your_model->some_function();
    ?>
    

    【讨论】:

    • 你不能在View中调用$this-&gt;load-&gt;model('your_model');,你只能在Controller中调用它。
    【解决方案3】:

    例如在User_controller加载用户模型$this-&gt;load-&gt;model('Users_model');

    然后用户查看页面$viewpage = this-&gt;Users_model-&gt;somefunction($id);

    【讨论】:

    • 您的建议答案对于MVC 结构化框架来说不是一个好习惯。
    猜你喜欢
    • 1970-01-01
    • 2018-06-24
    • 1970-01-01
    • 2021-09-24
    • 2019-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-19
    相关资源
    最近更新 更多