开发者

Codeigniter Model

I have a question about Jamie Rumbelow's MY_Model and models g开发者_如何学编程enerally. 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?


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.


If you wish to use Jamie Rumbelow's MY_Model untouched, you have to use only one table for each model, as it gets the table name from the model name. As he introduced it, this is a base CRUD model, you can extend it to fit your situation. I think the best practice is to use one table per model (not including the join tables if there are any). Although I sometimes skip this in CodeIgniter if some stuff can be added to the same model logically and are not too big to need their own model. For example there is a comment model and you need votes only for the comments. I do this out of laziness - I hate the manual model loading in CI.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜