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

Ted*_*Ted 2 php mysql codeigniter

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

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

Wes*_*rch 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`)
Run Code Online (Sandbox Code Playgroud)

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