Models
Models are optionally available for those who want to use a more traditional MVC approach.
- Nip_Model
- Anatomy of a Model
- Loading a Model
- Selecting Data
- Inserting Data
- Updating Data
- Deleting Data
- Restoring Data
- Relationship Data
Nip_Model?
Models are PHP classes that are designed to work with information in your database. For example, let's say you use NipIgniter to manage a user data. Here is an example of what such a model class might look like:
class User extends Nip_Model {
protected $tableName= "user";
protected $primary = "id";
protected $softDeletes = TRUE;
public $id;
public $username;
public $password;
public $email;
public $role_id;
public $created;
public $updated;
public $deleted;
public function __construct($options = array()){
parent::__construct($options);
}
public function getRole(){
return $this->belongsTo('Role','role_id');
}
}
Anatomy of a Model
Model classes are stored in your application/models/ folder. They can be nested within sub-folders if you want this type of organization.
The basic prototype for a model class is this:
class ModelName extends Nip_Model{
public function __construct($options = array()){
parent::__construct($options);
}
}
Where ModelName is the name of your class. Class names must have camelcase letter. Make sure your class extends the base Nip_Model class.
The file name will be the same as your class name. For example, if your class is this:
class UserModel extends Nip_Model{
public function __construct($options = array()){
parent::__construct($options);
}
}
Your file will be this:
application/models/UserModel.php
Loading a Model
Your models will typically be loaded and called from within your controller functions. To load a model you will use the following function:
$this->load->model('ModelName');
Once loaded, you will access your model functions using an object with the same name as your class:
$this->load->model('ModelName');
$this->ModelName->function();
If you would like your model assigned to a different object name you can specify it via the second parameter of the loading function:
$this->load->model('ModelName', 'fubar');
$this->fubar->function();
Selecting Data
$this->Model->all($options = array());
Permits you to load all row in the current Model with some $options. Example :
$result = $this->User->all(); // produce SELECT * FROM user var_dump($result);
If the parameters is empty, then the $result will produce all row from the user table
where
$where = array("role_id"=>"1", "active"=>"1");
$result = $this->User->all(array("where" => $where));
// produce SELECT * FROM user WHERE role_id = '1' AND active = '1'
var_dump($result);
$where = "role_id ='1' AND active = '1' OR username LIKE '%jhon%'";
$result = $this->User->all(array("where" => $where));
// produce SELECT * FROM user WHERE role_id = '1' AND active = '1' OR username LIKE '%jhon%'
var_dump($result);
fields
$fields = array("id", "username", "email", "role_id");
$result = $this->User->all(array("fields" => $fields));
// produce SELECT id, username, email, role_id FROM user
var_dump($result);
$fields = "id, username, email, role_id";
$result = $this->User->all(array("fields" => $fields));
// produce SELECT id, username, email, role_id FROM user
var_dump($result);
order_by
$orderBy = "id asc";
$result = $this->User->all(array("order_by" => $orderBy));
// produce SELECT * FROM user ORDER BY id asc
var_dump($result);
limit and offset
$limit = 10;
$result = $this->User->all(array("limit" => $limit));
// produce SELECT * FROM user LIMIT 10
var_dump($result);
$offset = 20;
$limit = 10;
$result = $this->User->all(array("limit" => $limit, "offset" => $offset));
// produce SELECT * FROM user LIMIT 20, 10 (in MySQL. Other databases have slightly different syntax)
var_dump($result);
$this->Model->first($where, $fields);
Permits you to load one row in the current Model. Example :
By primary key
$user = $this->User->first(1); // produce SELECT * FROM user where primary = 1 LIMIT 1 var_dump($user);
By some condition
$where = array("username" => "jhon", "password" => "doe");
$user = $this->User->first($where);
// produce SELECT * FROM user where username = 'jhon' AND password = 'doe' LIMIT 1
var_dump($user);
If there is no data with the condition, then it will returned NULL
$where = array("username" => "jhon", "password" => "doe");
$fields = "id, username, email, role_id";
$user = $this->User->first($where, $fields);
// produce SELECT id, username, email, role_id FROM user where username = 'jhon' AND password = 'doe' LIMIT 1
var_dump($user);
$this->Model->count($where);
Permits you to determine the number of rows in a particular table.
$totalRow = $this->User->count();
$totalRow = $this->User->count("status = '1'");
Inserting Data
$this->Model->save()
Nip_Model provide another way to insert data to the particular table. Create an object and set the properties value. Example :
$this->load->model("User");
$object = new User();
$object->username = "jhon";
$object->password = md5("doe");
$object->email = "[email protected]";
$object->role_id = 2;
$object->status_id = 2;
$obejct->save();
$this->load->model("User");
$data = array(
'username' => "jhon",
'password' => md5("doe"),
'email' => "[email protected]",
'role_id' => 2;
'status_id' => 2;
);
$object = new User($data);
$obejct->save();
$this->load->model("User");
$data = array(
'username' => "jhon",
'password' => md5("doe"),
'email' => "[email protected]",
'role_id' => 2;
'status_id' => 2;
);
$object = new User();
$object->attr($data);
$obejct->save();
Updating Data
$this->Model->save()
save() function will automatically detects whether to do an insert or update.
If the primary key value is available, then it will update the table.
$this->load->model("User");
$object = $this->User->first(1);
$object->password = md5("doedoe");
$object->status_id = 1;
$obejct->save();
$this->load->model("User");
$data = array(
'password' => md5("doedoe"),
'status_id' => 1;
);
$object = $this->User->first(1);
$object->attr($data);
$obejct->save();
Deleting Data
$this->Model->delete($where)
delete() function will run delete query for the table.
By primary key
$this->load->model("User");
$this->User->delete(1);
By some condition
$this->load->model("User");
$this->User->delete("status = 2");
SoftDelete
When soft deleting a model, it is not actually removed from your database. Instead, a deleted timestamp is set on the record.
class User extends Nip_Model{
public $softDeletes = TRUE;
}
$this->Model->forceDelete($where)
forceDelete() function will run delete query for the table if the softDeletes active.
By primary key
$this->load->model("User");
$this->User->forceDelete(1);
By some condition
$this->load->model("User");
$this->User->forceDelete("status = 2");
Restoring Data
$this->Model->restore($where)
restore() function will restore the deleted data in the table.
By primary key
$this->load->model("User");
$this->User->restore(1);
$this->Model->justTrash()
Only trash data that will be returned from the table.
$this->load->model("User");
$result = $this->User->justTrash()->all();
$this->Model->withTrash()
All data from database will be returned including the trash data.
$this->load->model("User");
$result = $this->User->withTrash()->all();
Relationship
Of course, your database tables are probably related to one another. For example, a blog post may have many comments. Nip_Model supports many types of relationships:
$this->Model->belongsTo($modelName = "ModelName", $foreignKey = "foreign_key_id")
You must define function to get the other table relationship.
class User extends Nip_Model{
public function getRole(){
return $this->belongsTo("Role", "role_id"); // role_id is the foreign key in the User table
}
}
$object = $this->User->first(1);
echo $object->role->id;
echo $object->role->title;
// getRole() can be called without 'get' but the first letter is lowercase. Example : getUserStatus() will be $object->userStatus->variable;
$this->Model->hasOne($modelName = "ModelName", $foreignKey = "foreign_key_id")
You must define function to get the other table relationship.
class User extends Nip_Model{
public function getPhone(){
return $this->hasOne("Phone", "user_id"); // user_id is the foreign key in the Phone table
}
}
$object = $this->User->first(1);
echo $object->phone->fax_number;
echo $object->phone->mobile_number;
// getPhone() can be called without 'get' but the first letter is lowercase. Example : getUserStatus() will be $object->userStatus->variable;
$this->Model->hasMany($modelName = "ModelName", $foreignKey = "foreign_key_id")
You must define function to get the other table relationship.
class User extends Nip_Model{
public function getPhotos(){
return $this->hasMany("Photos", "user_id"); // user_id is the foreign key in the Photos table
}
}
$object = $this->User->first(1);
$photos = $object->photos;
foreach($photos as $each){
echo '<img src="'.$each->path_image.'">';
}
// getPhotos() can be called without 'get' but the first letter is lowercase. Example : getUserStatus() will be $object->userStatus->variable;