你可以在CodeIgniter中链接模型调用 [英] Can you chain model calls in 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屋!