phpcodeignitermodel

Is it best practice to have more than one table in a Codeigniter model?


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.

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?


Solution

  • 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.

    class Post_model extends MY_Model
    {
        public function with_category()
        {
            $this->db->join('categories', 'categories.id = post.category_id', 'left');
            $this->db->select('categories.name AS category_name');
    
            return $this;
        }
    }
    

    We can then use our with_category() method (chained alongside all our built-in MY_Model methods) to pull out our category info:

    $this->post_model->with_category()
                     ->get_all();
    

    Or with get_by():

    $this->post_model->with_category()
                     ->get_by('status', 'open');
    

    Scoping is a cool way of introducing other tables into your models, while still getting to use all the cool stuff MY_Model provides.