I have integrated the Jamie Rumbelow My Model for doing active record queries with codeigniter from github - https://github.com/jamierumbelow/codeigniter-base-model
I'd like to use the normal codeigniter syntax for doing a where with multiple parameters but not sure how to use the standard codeigniter syntax as follows :
$this->db->where('active', 1);
$this->db->where('type', 'news');
Can anyone suggest how this is done using this MY_Model?
For instance... this works but only allows for one column & its value - how would I do this with multiple columns & values
$this->news_model->get_many_by('active', 1);
MY_Model's get_
methods accept the same parameters as CodeIgniter's query builder--formerly Active Record--'s where
. This means you can pass through an array:
$this->news_model->get_many_by(array( 'key' => 'value', 'other_key' => 'value' ));
If you're doing anything more complicated than this you could also create your own scoping method. Scoping methods are the *right* way of doing finds in MY_Model.
Scoping methods give context and readability to the find. In your example, you're finding active news articles, so we can create a scoping method on our model for those exact articles:
class News_model extends MY_Model
{
public function active_news()
{
$this->db->where('active', 1);
$this->db->where('type', 'news');
return $this;
}
}
Since we're returning $this
, we can chain these methods onto other MY_Model methods. In our controller:
$this->data['news'] = $this->news_model->active_news()->get_all();
This gives us a much more memorable, clearer and humane syntax to work with.
Sorted it - for anyone else having the same problem - you need to pass an array.
$this->news_model->get_many_by(
array('active' => 1, 'another_column'=> 'value')
);
This guide has everything you need to use MY_Model - consider it an unofficial manual/documentation!
You can do something like this for multiple conditions and to use the LIKE operation:
$conditions = [
'id' => $id
,'created_at LIKE' => $date.'%'
];
$object = $this->model1->get_by($conditions);
this will give you the query :
SELECT * FROM table WHERE id = "$id" AND created_at LIKE "$date"%