Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
C

CodeIgniter-MY_Model

> 编程语言
Open source

Base model (MY_Model) for the Codeigniter framework.

324 stars0 likes3 views
WebsiteGitHub

About

Base model (MY_Model) for the Codeigniter framework.

CodeIgniter-MY_Model

This CodeIgniter MY_Model is the result of a lengthy tutorial about constructing a MY_Model in CodeIgniter (http://avenir.ro/revisiting-my_model-copying-jamie-rumbelow-looking-eloquent/). It's based on Jamie Rumbelow's Base Model (https://github.com/jamierumbelow/codeigniter-base-model), but with some changed/added methods. It provides a full CRUD base for database interactions, as well as an event-based observer system, intelligent table name guessing and soft delete.

VERY IMPORTANT NOTE: MY_Model DOESN'T REPLACE THE QUERY BUILDER. IF YOU HAVE A VERY COMPLEX QUERY, DO NOT ASK MY_Model TO DO IT FOR YOU

Table of contents

  • Synopsis
  • Installation/Usage
  • CREATE
  • READ
  • Pagination
  • UPDATE
  • DELETE
  • Relationships
  • Working with relationships
  • Database Connection
  • Observers
  • Available methods

Synopsis

php
class User_model extends MY_Model { }

$this->load->model('user_model');

$this->user_model->get(1)

$this->user_model->get_all();

$this->user_model->where('username','avenirer')->get();

$this->user_model->insert(array('username' => 'avenirer','email' => '[email protected]'));

$this->user_model->update(array('status' => '0'), 1);

$this->user_model->delete(1);

Installation/Usage

Download and drag the MY_Model.php file into your application/core directory. CodeIgniter will load and initialise this class automatically.

Extend your model classes from MY_Model and all the functionality will be baked in automatically.

php
class User_model extends MY_Model
{
	public $table = 'users'; // you MUST mention the table name
	public $primary_key = 'id'; // you MUST mention the primary key
	public $fillable = array(); // If you want, you can set an array with the fields that can be filled by insert/update
	public $protected = array(); // ...Or you can set an array with the fields that cannot be filled by insert/update
	public function __construct()
	{
		parent::__construct();
	}
}

If extended like that, MY_Model makes the following assumptions:

  • there are at least a "created_at" and "updated_at" columns. wh If you want, you can be original by changing the settings before the parent::__construct();
…

CREATE

Inserting values

You can insert values by using the insert() method, passing it an array or an object as parameter. You can also insert multiple rows of data by using a multidimensional array.

php
'avenirer','email'=>'[email protected]');
$this->load->model('user_model');
$this->user_model->insert($insert_data);
?>

Inserting directly from forms with form validation

You can at any time directly insert values from forms into the tables using the from_form() method. First of all make sure you have a fillable or a protected property (at least the primary key should be in there), because you must make sure no-one interferes with your id's or whatever you use to uniquely identify the rows. Also is worth noting that, because the inserts and updates from forms are done directly without intervention from developer, YOU MUST DEFINE VALIDATION RULES FOR ALL FIELDS THAT YOU ARE FILLING

After you've done this, you must set the rules. If you use the MY_Model's form validation, I advise you to write the rules inside your model. This even allows you to specify separate rules for each action (i.e. insert and update) by using an associative array with keys according to the action. If the same ruleset should apply to all actions, just use an sequential array. Below you can find an example of model:

…

After setting the model this way, you are ready to go. So, in your controller you can go like this:

php
public function add_user()
{
	$this->load->model('user_model');
	$id = $this->user_model->from_form()->insert();
	if($id === FALSE)
	{
		$this->load->view('user_form_view');
	}
	else
	{
		echo  $id;
		//...whatever you want to do. the form was submitted and the data was inserted
	}
}

If you have any doubts, this is how the view looks:

php
user_model->from_form(NULL,array('created_by'=>'1'))->insert();
...

READ

Arrays vs Objects

By default, MY_Model is setup to return objects. If you'd like to return results as array you can:

  • either define $this->return_as = 'array' in the constructor
  • or add as_array() into the query chain:
php
$users = $this->user_model->as_array()->get_all(); $posts = $this->post_model->as_object()->get_all();

If you'd like all your calls to use the array methods, you can set the $return_type variable to array.

Return as dropdown

There are moments when you need to retrieve data to fill a select input type. For this we have a method called as_dropdown($field). This method will return an array having the primary keys as array keys and a $field as values:

php
$categories = $this->category_model->as_dropdown('title')->get_all();
echo form_dropdown($categories);

Caching

If you want to cache the result for faster output, you can at any time use the MY_Model's caching. To do this you simply attach a set_cache('name') inside the query chain:

php
$this->load->model('user_model');
$users = $this->user_model->as_array()->set_cache('get_all_users')->get_all();

The code above will create a cache file named mm_users_get_all_users. If you want the cache to have a time limit, you can pass a second parameter that represents the number of seconds:

php
$users = $this->user_model->as_array()->set_cache('get_all_users',3600)->get_all();

This file will then be used by the model whenever you call the get_all() method that has a set_cache('get_all_users') method in the chain.

Whenever you want, you can delete the cache "manually" by using the delete_cache() method.

There are three ways you can delete the cache:

  • delete_cache('get_all_users') deletes a certain cache;
  • delete_cache('*') deletes the caches that start with 'mm_users_' (where 'mm_users' is the prefix used by MY_Model in conjuction with your model's table name);
  • delete_cache() deletes all cache that start with 'mm_' (where 'mm_' is the prefix used by MY_Model).

Example:

php
$this->user_model->delete_cache('get_all_users');

Auto-delete caching

You can set the model in a way so that the cache will be deleted automatically whenever you write/update/delete data from your model's table. This way you won't need to do it manually. You can have this enabled by setting the delete_cache_on_save property to TRUE in the constructor:

php
class User_model extends MY_Model
{
    //public $soft_deletes = TRUE;
    public $delete_cache_on_save = TRUE;

    function __construct()
    {
        parent::__construct();
    }
    ...

Pagination

You can at any time "paginate" the results. You can do this by simply changing get_all() method with paginate() method. The paginate() method can receive up to three parameters:

  • first paramater, which is optional (default is set to 10) is the number of rows per page;
  • second parameter, which is optional (default is set to NULL), is the total of rows;
  • the third parameter, which is also optional (default is set to 1) is the page you want to get.

If you only passed the first parameter, the page number will be retrieved from the URL (the last segment of the page). If you didn't pass the second parameter you will only be able to output the previous and next page, without links to all the pages.

Examples:

php
$total_posts = $this->post_model->count_rows(); // retrieve the total number of posts
$posts = $this->post_model->paginate(10,$total_posts); // paginate with 10 rows per page
echo $this->post_model->all_pages; // will output links to all pages like this model: "". It will put a link if the page number is not the "current page"
echo $this->post_model->previous_page; // will output link to the previous page like this model: "post_model->next_page; // will output link to the next page like this model: ">". It will only put a link if there is a "next page"

Don't you like how the links look? You can change them by modifing the following properties inside the models that extend the MY_Model():

php
$this->pagination_delimiters = array('','');
$this->pagination_arrows = array('&lt;','&gt;');

Also, you can use the set_pagination_delimiters($delimiters) and set_pagination_arrows($arrows) methods, where $delimiters and $arrows are arrays.

UPDATE

The update() method

The basic update()

The update() method is pretty much the same as the insert() method.

To update some values you must pass an array with the columns as keys and their respective values as values of array. The second parameter can be either the id of the row or the column name used to identify the row:

Update using row id:

php
'avenirer','email'=>'[email protected]');
$this->load->model('user_model');
$this->user_model->update($update_data,2);
?>

Update using column name:

php
'avenirer','email'=>'[email protected]', 'id'=>'2');
$this->load->model('user_model');
$this->user_model->update($update_data,'email');
?>

You can also pass a multidimensional array to change multiple rows. In this case the second parameter should be the name of the identifying column.

Update using the where() method

Another method to do an update would be to use the update() method in conjuction with the where() method:

php
'avenirer','email'=>'[email protected]');
$this->load->model('user_model');
$this->user_model->where('email','[email protected]')->update($update_data);
?>

Update directly from form using from_form() method

The update can also be made directly from the form with validation, the same way as is done by the insert() method. The only difference would be that you need to specify which input field should be used as reference for the rows to be updated. You do this by passing a third parameter as array:

php
$this->user_model->from_form(NULL,NULL,array('user_id'))->update(); // where user_id is an input element

Also, if you want to reference the field with a direct value that doesn't exist within the form, then you can assign it within the array too.

php
$this->user_model->from_form(NULL,NULL,array('user_id' => 1))->update(); // where user_id is referenced directly

If you need to use another table field that is not in the form, in order to identify the row, you can pass it to the from_form() method as a second parameter:

php
$id = $this->user_model->from_form(NULL,array('created_by'=>'1'), array('user_id'))->update();

Update custom string with disabled escaping

You can prevent escaping content by passing an optional third argument, and setting it to FALSE (the second parameter is a where condition set as an array - you can set it to NULL):

php
$this->user_model->update(array('views'=>'views+1'), array('id'=>'1'), FALSE);

TAKE CARE: This doesn't work with values that have space inside unless you set quotes on them. So I would rather not use this (Maybe in future I will change the way this works)

DELETE

The delete() method

Soft Deletes

By default, the delete mechanism works with an SQL DELETE statement. However, you might not want to destroy the data, you might instead want to perform a 'soft delete'.

If you enable soft deleting, the deleted_at row will be filled with the current date and time, rather than actually being removed from the database.

You can enable soft delete in the constructor:

php
$this->soft_deletes = TRUE;

Once you've enabled it whenever you do, for example, a $this->user_model->delete(3); the delete() method will only create a datetime in the deleted_at column of the user with id 3.

If you really want to delete a row you can use force_delete() method:

php
$this-

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

PHP

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 18, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言