【问题标题】:Using a Model function in Controller在控制器中使用模型函数
【发布时间】:2011-06-02 17:52:54
【问题描述】:

在我名为Profile_model 的模型中,我有这个函数可以检索登录用户的配置文件数据。

function profile_read()
{
    $this->db->where('user_id', $this->tank_auth->get_user_id());
    $query = $this->db->get('user_profiles');
    $data['row'] = $query->row();
}

在我的控制器中,我使用$this->load->view('profile/edit_general_view', $data); 尝试将模型中的数据加载到视图中。

function edit_profile()
{       

    //validation rules
    $this->form_validation->set_rules('first_name', 'First Name', 'trim|required|xss_clean|min_length[2]|max_length[20]|alpha');
    $this->form_validation->set_rules('last_name', 'Last Name', 'trim|required|xss_clean|min_length[2]|max_length[20]|alpha');


    if ($this->form_validation->run() == FALSE) //if validation rule fails
    {           
        $this->load->view('profile/edit_general_view', $data); //load data from model in view
    }
    else //success
    {
        $send_to_db = array (                   
                'first_name'    => $this->input->post('first_name'),
                'last_name'     => $this->input->post('last_name')
        );
        $seg = 'edit';
        $this->load->model('Profile_model');
        $this->Profile_model->profile_update($send_to_db, $seg);            
    }
}

将数据从模型函数profile_read 传递到我的控制器函数的正确方法是什么?

【问题讨论】:

    标签: php mysql codeigniter


    【解决方案1】:

    是时候了解变量作用域了: http://php.net/manual/en/language.variables.scope.php

    控制器无法访问模型方法中的 $data 变量。让模型方法返回一个实际的数据数组。例如:

    function profile_read()
    {
        $this->db->where('user_id', $this->tank_auth->get_user_id());
        $query = $this->db->get('user_profiles');
        return ($query ? $query->row : FALSE);
    }
    

    然后在控制器中,将其存储在视图的“数据”中。

    【讨论】:

    • 啊,我现在明白了。是时候阅读一下returning values了。 @Cyber​​Junkie,这只是初级 PHP,只是为了让您知道它不一定与 Codeigniter 相关。
    • 谢谢!现在我可以使用 $this->load->model('Profile_model'); $data['row'] = $this->Profile_model->profile_read(); 在控制器中使用模型功能
    猜你喜欢
    • 2021-08-25
    • 1970-01-01
    • 2013-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多