使用Codeigniter和Active Record重用条件的最佳方法

时间:2011-05-22 20:51:33

标签: php mysql codeigniter

我正在处理一个需要运行4或5个数据库查询的控制器,所有这些查询都具有相同的基本条件。由于条件涉及大约十几个if / else语句,我希望避免在模型中重复它或者如果可能的话重新运行它5次。

是否有一种智能方法可以将模型函数中的WHERE子句重用于函数?

1 个答案:

答案 0 :(得分:5)

使用CI的Active Record Caching

示例(逐字逐句显示):

$this->db->start_cache();
$this->db->select('field1');
$this->db->stop_cache();

$this->db->get('tablename');

//Generates: SELECT `field1` FROM (`tablename`)

$this->db->select('field2');
$this->db->get('tablename');

//Generates: SELECT `field1`, `field2` FROM (`tablename`)

$this->db->flush_cache();

$this->db->select('field2');
$this->db->get('tablename');

//Generates: SELECT `field2` FROM (`tablename`)

WHERE子句也可以这种方式“缓存”,所以这应该是你需要的。如果必须,将一些缓存的AR调用移动到一个函数中,只需在模型中需要它的每个其他函数的开头调用该函数。每次运行查询时,都会调用缓存的函数,直到您flush_cache()

相关问题