Best way to reuse where conditions with Codeigniter and Active Record
I 开发者_StackOverflow中文版am working on a controller that needs to run 4 or 5 datatabase queries all with the same basic where conditions. Since the conditions involve around a dozen if/else statements I'd like to avoid duplicating it within the model or re-running it 5 times if possible.
Is there an intelligent way to reuse the WHERE clauses from model function to function?
Use CI's Active Record Caching.
Example (verbatim from the linked page):
$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
clauses can be "cached" this way as well, so this should be what you need. If you must, move some cached AR calls into a function, and simply call the function at the beginning of each other function that needs it in your model. Each time you run a query, the cached functions will be called until you flush_cache()
精彩评论