从模型发送$ data变量到View

时间:2012-11-07 14:50:06

标签: php codeigniter codeigniter-2

好的,所以我在控制器中有这段代码。但是,它都是数据库驱动的,应该真的在模型中 - 我明白了。但是,正如您在IF语句中看到的,我需要将$ data传递给我的视图。根据结果​​。我尝试在我的模型中的方法中粘贴这个编码块(通过控制器调用模型方法),但是$ data [update_prompt]字符串没有被视图调用...

如何将此代码转换为模型 - 将$ data值发送回我的控制器以嵌入我的视图?

    // show appropriate upgrade message if user has free account

    $id = $this->session->userdata('user_id'); 

    $this->db->select('subscription'); // select the subscription column
    $this->db->where('id', $id); //find id in table that matches session id
    $query = $this->db->get("subscriptions"); // connect to this database
    $subscribe = $query->result_array(); //returns the result of the above

    if($subscribe[0]['subscription'] == 'freebie') // if subscription column equals 'freebie' in the $subscribe array, do this:
    {
        $data['update_prompt'] = $this -> load -> view('shared/upgrade_subscription', '', TRUE); // adds view within view, $update_prompt
    }
    else 
    {
        $data['update_prompt'] = '';
    }

1 个答案:

答案 0 :(得分:2)

您可以在模型中添加一个函数,如下所示:

public function myModelFunction($id) {

    //we return row as we are looking up by primary key and are guaranteed only one row
    return $this->db->select('subscription')
                    ->where('id', $id)
                    ->get('subscriptions')
                    ->row();
}

然后,在你的控制器中:

public function myControllerFunction() {

    $subscribe = $this->my_model->myModelFunction($this->session->userdata('id'));
    if($subscribe->subscription == 'freebie') // if subscription column equals 'freebie' in the $subscribe array, do this:
    {
        $data['update_prompt'] = $this -> load -> view('shared/upgrade_subscription', '', TRUE); // adds view within view, $update_prompt
    }
    else 
    {
        $data['update_prompt'] = '';
    }
}