CodeIgniter Models

Models provide a way to interact with databases tables, there are much helper methods to interact with database tables as inserting, updating, fetching, deleting records.

Creating Models

<?php

namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model
{
    protected $table      = 'users';
    protected $primaryKey = 'id';
    protected $useAutoIncrement = true;
    protected $returnType     = 'array';
    protected $useSoftDeletes = true;
    protected $allowedFields = ['fname', 'lname', 'email', 'password'];
    protected $useTimestamps = true;
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
}

Finding Data

Return a single record

$record=$model->find($primary_key);

Return all results

$users = $model->findAll();

Return all results with where 

$users = $model->where('active', 1)->findAll();

Return first result 

$user = $model->where('id', 1)->first();

Saving data

$data=[
'fname'=>'Rama',
'lname'=>'Singh'
];
$model->insert($data);

Update Data

$data=[
'fname'=>'Rama',
'lname'=>'Singh'
];
$model->update($id, $data);

Delete data

$model->delete($id);

Delete with where clause

$model->where('id', 1)->delete();

Working with query builder

Create instance of query builder 

$builder = $model->builder();

Runtime Return Type changes

asArray()

$users= $model->asArray()->findAll()

asObject()

$users= $model->asObject()->findAll()

Query builder class

$model= new UserModel();
$builder=$model->builder();
$query = $builder->get();

Return all results as an object.

$query->getResult();

Return all results as an array.

$query->getResultArray();

Return single result as an object

$query->getRow();

Return single result as an array

$query->getRowArray();

Select specific columns from a table

$builder->select('fname, lname, email');

Select maximum of a column

$builder->selectMax('price');

Select minimum of a column

$builder->selectMin('price');

Select average of a column value

$builder->selectAvg('price')

Select sum of a column value

$builder->selectSum('price');

Select count of a column value

$builder->selectCount('price');

Join tables.

$builder->join('posts', 'posts.user_id = users.id', 'left');

Looking for specific data

$builder->where('field_name', 'value');
->where('name !=', $name)
->where('id <', $id);
->where(['name'=>'Rama', 'age'=>20]);

OR

->orWhere();

In

->whereIn($collection);

Looking for similar data.

$builder->like('title','computer is an electronic machine');

Popular Libraries

  • Cookies
  • Working with files
  • Image manipulation class
  • Pagination
  • Session library
  • Working with uploaded files
  • Validation

 

© 2016 - 2022, All Rights are Reserved.