php CodeIgniter 在视图中调用模型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21140379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
CodeIgniter calling model on view?
提问by Fatim
I have a view which comport a table of data, this data is generated on a model. How can I call this model in my view to be posted on my view...? That's the Equivalent of what I want to do with codeIgniter on php :
我有一个包含数据表的视图,该数据是在模型上生成的。我怎样才能在我的视图中调用这个模型来发布在我的视图上......?这与我想在 php 上使用 codeIgniter 做的事情等效:
while($row = mysql_fetch_array($requet))
{
// code of displaying my data;
}
回答by Mohammed Sufian
try using
$CI =& get_instance()
尝试使用
$CI =& get_instance()
then load your model like this:
然后像这样加载你的模型:
$CI->load->model('someModel')
$CI->load->model('someModel')
then call your model function like this:
然后像这样调用你的模型函数:
$result = $CI->someModel->somefunction()
$result = $CI->someModel->somefunction()
then display using foreach
然后使用foreach显示
foreach($result as $row){ $row->somecolumnName }
foreach($result as $row){ $row->somecolumnName }
回答by Jice06
I think it is not a good idea to call a model directly from the view.
我认为直接从视图中调用模型不是一个好主意。
Your controller must get data from the model then send it to your view
您的控制器必须从模型中获取数据,然后将其发送到您的视图
$this->load->model('my_model');
$my_data['my_array'] = $this->my_model->get_my_data();
$this->load->view('your_view', $my_data);
In your view use it like this
在您看来,像这样使用它
foreach($my_array as $item){
echo $item;
}
回答by Engr Zardari
i called model method like this.
我像这样调用模型方法。
<?php
$CI =& get_instance();
$CI->load->model('MyModel');
$result= $CI->MyModel->MyMethod($parameter)->result_array();
foreach($result as $row){
echo $row['column_name'];
}
?>
回答by CodeCanyon
First Model interacts withe the database.Then load the model and access relevant function in your controller.Finally load the data to view from the controller.That's it...you can show the data simply in a foreach loop.
首先模型与数据库交互。然后加载模型并访问控制器中的相关功能。最后加载数据以从控制器查看。就是这样......你可以简单地在 foreach 循环中显示数据。
回答by Igor S.
You can call model functions form view. Remember: This solution is against MVC pattern
您可以在视图中调用模型函数。请记住:此解决方案是针对 MVC 模式的
Model:
模型:
function getdata() {
$query = $this->db->query($sql);
return $query->result_array();
}
View:
看法:
foreach($this->modelname->getdata() as $item) {
}

