我刚刚在模型中创建了这个函数,看看我在社交网络中关注的是谁...我如何在视图中调用它?
function isfollowing($following){
$user_id = $this->session->userdata('uid');
$this->db->select('*');
$this->db->from('membership');
$this->db->join('following', "membership.id = following.tofollow_id");
$this->db->where("tofollow_id","$following");
$this->db->where("user_id", "$user_id");
$q = $this->db->get();
if($q->num_rows() > 0) {
return "yes";
} else {
return "no";
}
}
现在在我的视图中我如何称之为我已经创建了一个函数来获取当前登录用户的ID并且等于$ r-> id
我怎么称呼它?在if语句中的“==”之后会发生什么?
观点
<?php if ( $r->id == ): ?>
答案 0 :(得分:2)
从视图中调用模型函数不是一个好习惯。 有一些替代品。你可以使用你喜欢的任何人。
第一
当您加载视图时,请调用模型函数并将其传递给变量 将此变量传递给视图。
控制器
$following_status = $this->my_model->isfollowing($following);
$data['following_status'] = $following_status;
$this->load->view('my_view',$data);
查看
<p>$following_status</p>
谢胜利
如果您想独立于模特,您可以创建帮助 在应用程序的任何地方使用您必须创建一个CI实例 让它工作。
custom_helper.php
function isfollowing($following)
{
$CI = get_instance();
$user_id = $CI->session->userdata('uid');
$CI->db->select('*');
$CI->db->from('membership');
$CI->db->join('following', "membership.id = following.tofollow_id");
$CI->db->where("tofollow_id","$following");
$CI->db->where("user_id", "$user_id");
$q = $CI->db->get();
if($q->num_rows() > 0) {
return "yes";
} else {
return "no";
}
}
查看
//load the custom helper before using it (you can autoload of in autoload.php)
//or use common way $this->load->helper('custom');
<p>isfollowing($yourparameter)</p>
答案 1 :(得分:0)
您执行以下操作:
(1)将模型加载到创建页面的控制器中或自动加载
(2)在您的视图中,键入以下内容:
$this->The_custom_model->isfollowing($theinputvariable)
其中The_custom_model
是您定义isfollowing()
函数的模型。
$theinputvariable
是函数的适当参数值。请记住,您已将对象指定为函数的参数,因此您需要考虑这一点。
答案 2 :(得分:0)
这是raheel发布的一个修正版本,显示了一个if检查 - 可能对你的问题没有必要,但是给你一些思考的东西......
// check to see if anything come back from the database?
if ( ! $data['following_status'] = $this->my_model->isfollowing($following) ) {
// nothing came back, jump to another method to deal with it
$this->noFollowers() ; }
// else we have a result, and its already set to data, so ready to go
else {
// do more here, call your view, etc
}
即使网页正在运行,数据库也可能会崩溃,因此养成检查结果的习惯是很好的。您可以在控制器和模型中执行的错误检查越多,视图文件就越清晰。
答案 3 :(得分:0)
要在您的视图中访问模型,请先将其加载到自动加载文件中,如下所示
$autoload['model'] = array('model_name');
然后在视图中你可以通过使用这行代码
来获得它 $this->model_name->isfollowing($following)
正在跟踪,您将通过 tofollow_id