duanquanzhi5560 2018-06-30 12:31
浏览 34
已采纳

在不破坏MVC框架的情况下在CodeIgniter中加载模型

I'm really a newbie in MVC Framework and as well as in CodeIgniter. Is it possible to access model in view in CodeIgniter without breaking MVC framework? This is what I'm talking about.

Below is my code for my view.

foreach ($packages as $row)
{
    if($row->Category == "Wedding")
    {
        $package_name = $row->package_name;
        $ratings = $model->ratings($package_name);
        foreach ($ratings as $row_review)
        {

        }
    }
}

And this is in my model

public function ratings($package_name)
{
    $this->db->select('round(sum(Rating)/count(Rating)) as total');
    $this->db->where('package_name', $package_name);
    $query = $this->db->get('tbl_review');
    return $query->result();
}
  • 写回答

2条回答 默认 最新

  • doushi1974 2018-06-30 13:22
    关注

    Hope this will help you :

    Note : your database and model should also be loaded either in controller or in autoload.php;

    You can do it with the help of condeigniter's helpers . Create a file and name it custom_helper.php and add it to helpers folder and load it with autoload.php like this :

    $autoload['helper'] = array('custom');
    

    In your custom_helper.php add a function like this :

    function package_ratings($package_name)
    { 
        $ci = & get_instance();
        $ci->db->select('round(sum(Rating)/count(Rating)) as total'); 
        $ci->db->where('package_name',$package_name);
        $query = $ci->db->get('tbl_review'); 
        return $query->result(); 
    }
    

    In your view use package_ratings function as the given below :

    foreach($packages as $row)
    { 
        if($row->Category == "Wedding")
        { 
            $package_name = $row->package_name; 
            $ratings = package_ratings($package_name); 
            foreach ($ratings as $row_review) 
            { 
    
            }
        }
    }
    

    For more : https://www.codeigniter.com/user_guide/general/helpers.html

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面
  • ¥15 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥15 C# datagridview 栏位进度