Reputation: 4188
Using https://github.com/jamierumbelow/codeigniter-base-model, how can I dynamicaly chnage the table name used in a model?
I have some models that are very similar, one set used by users in Group A and the others by users in Group B.
To save some coding and to make things neater, I'd like to consolidate the models, and would therefore need to pass along the group, and change the table depending on the group passed.
I know I can set the table name underneath the start of the model class, but I'm wondering how I can set it dynamically any time a model method is called?
Here is some test code I have:
function setGroup($group)
{
switch($group) {
case 'admin':
case 'mod':
$this->table = 'library_categories';
break;
case 'members':
$this->table = 'user_categories';
break;
}
return $this;
}
This doesn't work.
If I name the model after the table for Group A, e.g. group_a_model.php, then even setting the table for Group B ($this->table = 'group_b') doesnt actually change the table for the query.
I tried giving the model a generic name (group_model) but then I have to set "public $table = 'group_a')" in the model. Again, the code provided won't actually change the table used, it always uses table group_a...
Is there a way to change the table used, using this MY_Model helper?
Upvotes: 0
Views: 120
Reputation: 2930
There is no $this->table
in that library.
There is a $this->_table
, which is used by the library to identify the table.. but unfortunately that property is protected, so you cannot change it's value from outside the class.
Adding the following method to the class:
public function setTable($table)
{
$this->_table = $table;
}
would mean you can now set the table name using $this->setTable('a_db_table');
You can add that method by either directly editing the class file. Or by subclassing that class with your own class.. for example:
class custom_model extends MY_Model{
//put the method I mentioned earlier here
}
Upvotes: 1