0

我刚刚在模型中创建了这个函数来查看我在我的社交网络中关注的人......我如何在视图中调用它?

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 == ): ?>
4

4 回答 4

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>
于 2013-03-16T01:44:42.597 回答
0

您执行以下操作:

(1) 在创建页面的控制器中加载模型或自动加载它

(2) 在您看来,键入如下内容:

$this->The_custom_model->isfollowing($theinputvariable)

The_custom_model你定义函数的模型在哪里isfollowing()

$theinputvariable是您的函数的适当参数值。请记住,您已将对象指定为函数的参数,因此您需要考虑这一点。

于 2013-03-16T00:36:54.627 回答
0

要将模型访问到您的视图中,您首先将其加载到自动加载文件中,如下所示

   $autoload['model'] = array('model_name');

然后在视图中您可以通过使用这行代码来获取它

     $this->model_name->isfollowing($following)

在下面你将传递你tofollow_id

于 2013-03-16T06:45:53.993 回答
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 
 } 

即使网页正在运行,数据库也可能出现故障,因此养成检查结果的习惯是件好事。您可以在控制器和模型中进行的错误检查越多,您的视图文件就会越干净。

于 2013-03-16T03:21:14.420 回答