你可以在CodeIgniter中链接模型调用 [英] Can you chain model calls in CodeIgniter

查看:143
本文介绍了你可以在CodeIgniter中链接模型调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图确保我最大限度地利用我的模型类,我最近刚刚接触MVC中的M。假设你的模型中存在这样的函数:

  public function by_year($ year)
{
$ this-> db-> where('EXTRACT(YEAR FROM post_date)='。$ year);
}

public function by_month($ month)
{
$ this-> db-> where('EXTRACT(MONTH FROM post_date)='。 $ month);
}

您可以像使用活动记录类一样将这些调用链接在一起? p>

  $ this-> db-> select('*') - > from('table'); 
$ this-> model_name-> by_year($ year) - > by_month($ month);
$ results = $ this-> db-> get() - > result_array();
print_r($ results);

或者,如果有一种方法可以在1行代码中执行,显然上面的方法不工作,我得到一个错误致命错误:调用成员函数by_month()对非对象

$是的,您可以通过向每个方法添加 return $ this 。 p>

  public function by_year($ year)
{
$ this-> db-& EXTRACT(YDAR FROM post_date)='。$ year);
return $ this;
}

public function by_month($ month)
{
$ this-> db-> where('EXTRACT(MONTH FROM post_date)='。 $ month);
return $ this;
}

这只适用于PHP 5.


I'm trying to ensure I'm getting the most out of my models class, and I am recently new to the M in MVC. Assuming that in your model there exists functions like this:

public function by_year($year)
{
    $this->db->where('EXTRACT(YEAR FROM post_date) = '.$year);
}

public function by_month($month)
{
    $this->db->where('EXTRACT(MONTH FROM post_date) = '.$month);
}

Can you chain these calls together like when using the active record class?

$this->db->select('*')->from('table');
$this->model_name->by_year($year)->by_month($month);
$results = $this->db->get()->result_array();
print_r($results);

Alternately if there is a way to execute this in 1 line of code that would be better for me. Obviously the above method doesn't work, and I'm getting an error Fatal error: Call to a member function by_month() on a non-object

解决方案

Yes, you can, by adding a return $this to each method.

public function by_year($year)
{
    $this->db->where('EXTRACT(YEAR FROM post_date) = '.$year);
    return $this;
}

public function by_month($month)
{
    $this->db->where('EXTRACT(MONTH FROM post_date) = '.$month);
    return $this;
}

This will only work with PHP 5.

这篇关于你可以在CodeIgniter中链接模型调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆