I have a question about Jamie Rumbelow’s MY_Model and models generally. MY_Model provides a protected variable that holds the name of the table. I want to use it but I want my model to handle 3 tables. So I guess my question is can a model handle more than one table? is it good practice to do this or is it better to have a model per database table?
I have a question about Jamie Rumbelow’s MY_Model and models generally. MY_Model provides a
Share
By default, MY_Model doesn’t support multiple tables, however, you can very easily create methods – I like to call them scopes – to link to other tables in an efficient and elegant manner.
Let’s say we have a post_model.php that needs to pull in data from the categories table. I’ll assume that we want to bring in our category.name based on the post.category_id.
We can then use our
with_category()method (chained alongside all our built-in MY_Model methods) to pull out our category info:Or with
get_by():Scoping is a cool way of introducing other tables into your models, while still getting to use all the cool stuff MY_Model provides.