1. Go to this page and download the library: Download yidas/codeigniter-model library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
yidas / codeigniter-model example snippets
$this->load->model('Posts_model');
// Create an Active Record
$post = new Posts_model;
$post->title = 'CI3'; // Equivalent to `$post['title'] = 'CI3';`
$post->save();
// Update the Active Record found by primary key
$post = $this->Posts_model->findOne(1);
if ($post) {
$oldTitle = $post->title; // Equivalent to `$oldTitle = $post['title'];`
$post->title = 'New CI3';
$post->save();
}
$result = $this->Posts_model->insert(['title' => 'Codeigniter Model']);
// Find out the record which just be inserted
$record = $this->Posts_model->find()
->order_by('id', 'DESC')
->get()
->row_array();
// Update the record
$result = $this->Posts_model->update(['title' => 'CI3 Model'], $record['id']);
// Delete the record
$result = $this->Posts_model->delete($record['id']);
$config['composer_autoload'] = TRUE;
class Post_model extends yidas\Model {}
class My_model extends yidas\Model
{
protected $primaryKey = 'sn';
const CREATED_AT = 'created_time';
const UPDATED_AT = 'updated_time';
// Customized Configurations for your app...
}
class Post_model extends My_model
{
protected $table = "post_table";
}
// Without any scopes & conditions for this query
$records = $this->Model->find(true)
->where('is_deleted', '1')
->get()
->result_array();
// This is equal to find(true) method
$this->Model->withAll()->find();
// Find conditions first then call again
$this->Model->find()->where('id', 123);
$result = $this->Model->update(['status'=>'off']);
// Counter set usage equal to `UPDATE mytable SET count = count+1 WHERE id = 123`
$this->Model->getDB()->set('count','count + 1', FALSE);
$this->Model->find()->where('id', 123);
$result = $this->Model->update([]);
public integer batchUpdate(array $dataSet, boolean $withAll=false, interger $maxLength=4*1024*1024, $runValidation=true)
// Find a single active record whose primary key value is 10
$activeRecord = $this->Model->findOne(10);
// Find the first active record whose type is 'A' and whose status is 1
$activeRecord = $this->Model->findOne(['type' => 'A', 'status' => 1]);
// Query builder ORM usage
$this->Model->find()->where('id', 10);
$activeRecord = $this->Model->findOne();
public array findAll(array $condition=[], integer|array $limit=null)
// Find the active records whose primary key value is 10, 11 or 12.
$activeRecords = $this->Model->findAll([10, 11, 12]);
// Find the active recordd whose type is 'A' and whose status is 1
$activeRecords = $this->Model->findAll(['type' => 'A', 'status' => 1]);
// Query builder ORM usage
$this->Model->find()->where_in('id', [10, 11, 12]);
$activeRecords = $this->Model->findAll();
// Print all properties for each active record from array
foreach ($activeRecords as $activeRecord) {
print_r($activeRecord->toArray());
}
public boolean beforeSave(boolean $insert, array $changedAttributes)
public CI_DB_query_builder hasOne(string $modelName, string $foreignKey=null, string $localKey=null)
class OrdersModel extends yidas\Model
{
// ...
public function customer()
{
return $this->hasOne('CustomersModel', 'id', 'customer_id');
}
}
$this->load->model('OrdersModel');
// SELECT * FROM `orders` WHERE `id` = 321
$order = $this->OrdersModel->findOne(321);
// SELECT * FROM `customers` WHERE `customer_id` = 321
// $customer is a Customers active record
$customer = $order->customer;
public CI_DB_query_builder hasMany(string $modelName, string $foreignKey=null, string $localKey=null)
class CustomersModel extends yidas\Model
{
// ...
public function orders()
{
return $this->hasMany('OrdersModel', 'customer_id', 'id');
}
}
$this->load->model('CustomersModel');
// SELECT * FROM `customers` WHERE `id` = 123
$customer = $this->CustomersModel->findOne(123);
// SELECT * FROM `order` WHERE `customer_id` = 123
// $orders is an array of Orders active records
$orders = $customer->orders;
public array toArray()
class My_model extends yidas\Model
{
const SOFT_DELETED = 'is_deleted';
}
class My_model extends yidas\Model
{
const SOFT_DELETED = 'is_deleted';
// The actived value for SOFT_DELETED
protected $softDeletedFalseValue = '0';
// The deleted value for SOFT_DELETED
protected $softDeletedTrueValue = '1';
const DELETED_AT = 'deleted_at';
}
// class My_model extends yidas\Model
class Log_model extends My_model
{
const SOFT_DELETED = false;
}
class My_model extends yidas\Model
{
protected $userAttribute = 'uid';
/**
* Override _globalScopes with User validation
*/
protected function _globalScopes()
{
$this->db->where(
$this->_field($this->userAttribute),
$this->config->item('user_id')
);
return parent::_globalScopes();
}
public self withoutGlobalScopes()
$this->Model->withoutGlobalScopes()->find();
public self withAll()
$this->Model->withAll()->find();
public boolean validate($data=[], $returnData=false)
$this->load->model('PostsModel');
if ($this->PostsModel->validate($inputData)) {
// all inputs are valid
} else {
// validation failed: $errors is an array containing error messages
$errors = $this->PostsModel->getErrors();
}
$this->load->model('PostsModel');
$post = new PostsModel;
$post->title = '';
// ORM assigned or modified attributes will be validated by calling `validate()` without parameters
if ($post->validate()) {
// Already performing `validate()` so that turn false for $runValidation
$result = $post->save(false);
} else {
// validation failed: $errors is an array containing error messages
$errors = post->getErrors();
}
public array getErrors()
public array rules()
class PostsModel extends yidas\Model
{
protected $table = "posts";
/**
* Override rules function with validation rules setting
*/
public function rules()
{
return [
[
'field' => 'title',
'rules' => '
public function rules()
{
/**
* Set CodeIgniter language
* @see https://www.codeigniter.com/userguide3/libraries/language.html
*/
$this->lang->load('error_messages', 'en-US');
return [
[
'field' => 'title',
'rules' => '
$lang[''min_length'] = '`%s`
public array filters()
public function filters()
{
return [
[['title', 'name'], 'trim'], // Perform `trim()` for title & name input data
[['title'], 'static::method'], // Perform `public static function method($value)` in this model
[['name'], function($value) { // Perform defined anonymous function. 'value' => '[Filtered]value'
return "[Filtered]" . $value;
}],
[['content'], [$this->security, 'xss_clean']], // Perform CodeIgniter XSS Filtering for content input data
];
}
class My_model extends yidas\Model
{
function __construct()
{
$this->database = $this->db;
$this->databaseRead = $this->dbr;
parent::__construct();
}
}