PHP code example of yidas / codeigniter-model

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();
}

$records = $this->Posts_model->find()
    ->select('*')
    ->where('is_public', '1')
    ->limit(25)
    ->order_by('id')
    ->get()
    ->result_array();

$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";
}

$this->load->model('post_model', 'PostModel');

$post = $this->PostModel->findOne(123);

// class My_model extends yidas\Model
class Post_model extends My_model
{
    protected $table = "post_table";
}

$tableName = $this->PostModel->getTable();

class My_model extends yidas\Model
{
    protected $primaryKey = "sn";
}

class My_model extends yidas\Model
{
    protected $timestamps = false;
}

class My_model extends yidas\Model
{
    /**
     * Date format for timestamps.
     *
     * @var string unixtime(946684800)|datetime(2000-01-01 00:00:00)
     */
    protected $dateFormat = 'datetime';
}

class My_model extends yidas\Model
{
    const CREATED_AT = 'created_time';
    const UPDATED_AT = 'updated_time';
}

class My_model extends yidas\Model
{
    const CREATED_AT = 'created_time';
    const UPDATED_AT = NULL;
}

class My_model extends yidas\Model
{
    protected $database = 'database2';
}

class My_model extends yidas\Model
{
    // Enable ORM property check for write
    protected $propertyCheck = true;
}

$this->load->model('post_model', 'Model');

public CI_DB_query_builder find(boolean $withAll=false)

$records = $this->Model->find()
    ->select('*')
    ->where('is_public', '1')
    ->limit(25)
    ->order_by('id')
    ->get()
    ->result_array();

// 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();

$queryBuilder = $this->Model->find();
if ($filter) {
    $queryBuilder->where('filter', $filter);
}
$records = $queryBuilder->get()->result_array();

public self reset()

$this->Model->reset()->find();

public boolean insert(array $attributes, $runValidation=true)

$result = $this->Model->insert([
    'name' => 'Nick Tsai',
    'email' => '[email protected]',
]);

public integer batchInsert(array $data, $runValidation=true)

$result = $this->Model->batchInsert([
     ['name' => 'Nick Tsai', 'email' => '[email protected]'],
     ['name' => 'Yidas', 'email' => '[email protected]']
]);

public boolean replace(array $attributes, $runValidation=true)

$result = $this->Model->replace([
    'id' => 1,
    'name' => 'Nick Tsai',
    'email' => '[email protected]',
]);

public boolean update(array $attributes, array|string $condition=NULL, $runValidation=true)

$result = $this->Model->update(['status'=>'off'], 123)

// 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)

$result = $this->Model->batchUpdate([
    [['title'=>'A1', 'modified'=>'1'], ['id'=>1]],
    [['title'=>'A2', 'modified'=>'1'], ['id'=>2]],
]);

public boolean delete(array|string $condition=NULL, boolean $forceDelete=false, array $attributes=[])

$result = $this->Model->delete(123)

// Find conditions first then call again
$this->Model->find()->where('id', 123);
$result = $this->Model->delete();

// Force delete for SOFT_DELETED mode 
$this->Model->delete(123, true);

$result = $this->Model->insert(['name' => 'Nick Tsai']);
$lastInsertID = $this->Model->getLastInsertID();

public integer|string getLastInsertID()

$result = $this->Model->update(['name' => 'Nick Tsai'], 32);
$affectedRows = $this->Model->getAffectedRows();

public integer count(boolean $resetQuery=true)

$result = $this->Model->find()->where("age <", 20);
$totalCount = $this->Model->count();

public self setAlias(string $alias)

$query = $this->Model->setAlias("A1")
    ->find()
    ->join('table2 AS A2', 'A1.id = A2.id');

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

$post = new Posts_model;
$post->title = 'CI3';
$result = $post->save();

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

$post = $this->Posts_model->findOne(1);
if ($post) {
    $post->title = 'New CI3';
    $result = $post->save();
}

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

$post = $this->Posts_model->findOne(1);
$result = $post->delete();

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

// Set attributes
$post = new Posts_model;
$post->title = 'CI3';
$post['subtitle'] = 'PHP';
$post->save();

// Get attributes
$post = $this->Posts_model->findOne(1);
$title = $post->title;
$subtitle = $post['subtitle'];

class CustomersModel extends yidas\Model
{
    // ...

    public function orders()
    {
        return $this->hasMany('OrdersModel', ['customer_id' => 'id']);
    }
}

$orders = $this->CustomersModel->findOne(1)->orders;

$customer = $this->CustomersModel->findOne(1)

$orders = $customer->orders()->where('active', 1)->get()->result_array();

public object findOne(array $condition=[])

// 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());
}

// LIMIT 10
$activeRecords = $this->Model->findAll([], 10);

// OFFSET 50, LIMIT 10
$activeRecords = $this->Model->findAll([], [50, 10]);

public boolean save(boolean $runValidation=true)

public boolean beforeSave(boolean $insert)

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;
}

public boolean forceDelete($condition=null)

$result = $this->Model->forceDelete(123)

// Query builder ORM usage
$this->Model->find()->where('id', 123);
$result = $this->Model->forceDelete();

public boolean restore($condition=null)

$result = $this->Model->restore(123)

// Query builder ORM usage
$this->Model->withTrashed()->find()->where('id', 123);
$this->Model->restore();

public self withTrashed()

$this->Model->withTrashed()->find();

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();
    }
}

class My_model extends yidas\Model
{
    protected $database = 'default';
    
    protected $databaseRead = 'slave';
}

class My_model extends yidas\Model
{
    protected $databaseRead = [
        'dsn'   => '',
        'hostname' => 'specified_db_host',
        // Database Configuration...
        ];
}

$slaveHosts = ['192.168.1.2', '192.168.1.3'];

$db['slave']['hostname'] = $slaveHosts[mt_rand(0, count($slaveHosts) - 1)];

class My_model extends yidas\Model
{
    protected $databaseRead = 'slave';
}

public function beforeSave($insert)
{
    if (!parent::beforeSave($insert)) {
        return false;
    }

    // ...custom code here...
    return true;
}
php
$this->db->close();
$this->db->initialize();
php
$this->Model->find()->where('id', 123);
$result = $this->Model->sharedLock()->row_array();
php
$this->Model->find()->where('id', 123);
$result = $this->Model->lockForUpdate()->row_array();
php
$this->Model->getDB()->trans_start();
$this->Model->find()->where('id', 123)
$result = $this->Model->lockForUpdate()->row_array();
$this->Model->getDB()->trans_complete(); 
php
public array indexBy(array & $array, Integer $key=null, Boolean $obj2Array=false)
php
$records = $this->Model->findAll();
$this->Model->indexBy($records, 'sn');

// Result example of $records:
[
    7 => ['sn'=>7, title=>'Foo'],
    13 => ['sn'=>13, title=>'Bar']
]