\CodeIgniterModel

Class Model

The Model class provides a number of convenient features that makes working with a database table less painful.

It will:

  • automatically connect to database
  • allow intermingling calls between db connection, the builder, and methods in this class.
  • simplifies pagination
  • removes the need to use Result object directly in most cases
  • allow specifying the return type (array, object, etc) with each call
  • ensure validation is run against objects when saving items

Summary

Methods
Properties
Constants
__construct()
find()
findColumn()
findAll()
first()
set()
save()
classToArray()
getInsertID()
insert()
insertBatch()
update()
updateBatch()
delete()
purgeDeleted()
withDeleted()
onlyDeleted()
replace()
asArray()
asObject()
chunk()
paginate()
protect()
setTable()
errors()
skipValidation()
setValidationMessages()
setValidationMessage()
validate()
getValidationRules()
getValidationMessages()
countAllResults()
__get()
__isset()
__call()
$pager
No constants found
builder()
doProtectFields()
setDate()
cleanValidationRules()
fillPlaceholders()
trigger()
$table
$primaryKey
$insertID
$DBGroup
$returnType
$useSoftDeletes
$allowedFields
$useTimestamps
$dateFormat
$createdField
$updatedField
$tempUseSoftDeletes
$deletedField
$tempReturnType
$protectFields
$db
$builder
$validationRules
$validationMessages
$skipValidation
$validation
$beforeInsert
$afterInsert
$beforeUpdate
$afterUpdate
$afterFind
$beforeDelete
$afterDelete
$tempData
N/A
No private methods found
No private properties found
N/A

Properties

$pager

$pager : \CodeIgniter\Pager\Pager

Pager instance.

Populated after calling $this->paginate()

Type

\CodeIgniter\Pager\Pager

$table

$table : string

Name of database table

Type

string

$primaryKey

$primaryKey : string

The table's primary key.

Type

string

$insertID

$insertID : integer

Last insert ID

Type

integer

$DBGroup

$DBGroup : string

The Database connection group that should be instantiated.

Type

string

$returnType

$returnType : string

The format that the results should be returned as.

Will be overridden if the as* methods are used.

Type

string

$useSoftDeletes

$useSoftDeletes : boolean

If this model should use "softDeletes" and simply set a date when rows are deleted, or do hard deletes.

Type

boolean

$allowedFields

$allowedFields : array

An array of field names that are allowed to be set by the user in inserts/updates.

Type

array

$useTimestamps

$useTimestamps : boolean

If true, will set created_at, and updated_at values during insert and update routines.

Type

boolean

$dateFormat

$dateFormat : string

The type of column that created_at and updated_at are expected to.

Allowed: 'datetime', 'date', 'int'

Type

string

$createdField

$createdField : string

The column used for insert timestamps

Type

string

$updatedField

$updatedField : string

The column used for update timestamps

Type

string

$tempUseSoftDeletes

$tempUseSoftDeletes : boolean

Used by withDeleted to override the model's softDelete setting.

Type

boolean

$deletedField

$deletedField : string

The column used to save soft delete state

Type

string

$tempReturnType

$tempReturnType : string

Used by asArray and asObject to provide temporary overrides of model default.

Type

string

$protectFields

$protectFields : boolean

Whether we should limit fields in inserts and updates to those available in $allowedFields or not.

Type

boolean

$builder

$builder : \CodeIgniter\Database\BaseBuilder

Query Builder object

Type

\CodeIgniter\Database\BaseBuilder

$validationRules

$validationRules : array

Rules used to validate data in insert, update, and save methods.

The array must match the format of data passed to the Validation library.

Type

array

$validationMessages

$validationMessages : array

Contains any custom error messages to be used during data validation.

Type

array

$skipValidation

$skipValidation : boolean

Skip the model's validation. Used in conjunction with skipValidation() to skip data validation for any future calls.

Type

boolean

$beforeInsert

$beforeInsert : \CodeIgniter\type

Callbacks for beforeInsert

Type

\CodeIgniter\type

$afterInsert

$afterInsert : \CodeIgniter\type

Callbacks for afterInsert

Type

\CodeIgniter\type

$beforeUpdate

$beforeUpdate : \CodeIgniter\type

Callbacks for beforeUpdate

Type

\CodeIgniter\type

$afterUpdate

$afterUpdate : \CodeIgniter\type

Callbacks for afterUpdate

Type

\CodeIgniter\type

$afterFind

$afterFind : \CodeIgniter\type

Callbacks for afterFind

Type

\CodeIgniter\type

$beforeDelete

$beforeDelete : \CodeIgniter\type

Callbacks for beforeDelete

Type

\CodeIgniter\type

$afterDelete

$afterDelete : \CodeIgniter\type

Callbacks for afterDelete

Type

\CodeIgniter\type

$tempData

$tempData : array

Holds information passed in via 'set' so that we can capture it (not the builder) and ensure it gets validated first.

Type

array

Methods

find()

find(mixed|array|null  $id = null) : array|object|null

Fetches the row of database from $this->table with a primary key matching $id.

Parameters

mixed|array|null $id

One primary key or an array of primary keys

Returns

array|object|null —

The resulting row of data, or null.

findColumn()

findColumn(string  $columnName) : array|null

Fetches the column of database from $this->table

Parameters

string $columnName

Throws

\CodeIgniter\Database\Exceptions\DataException

Returns

array|null —

The resulting row of data, or null if no data found.

findAll()

findAll(integer  $limit, integer  $offset) : array|null

Works with the current Query Builder instance to return all results, while optionally limiting them.

Parameters

integer $limit
integer $offset

Returns

array|null

first()

first() : array|object|null

Returns the first row of the result set. Will take any previous Query Builder calls into account when determining the result set.

Returns

array|object|null

set()

set(mixed  $key, string  $value = '', boolean|null  $escape = null) : $this

Captures the builder's set() method so that we can validate the data here. This allows it to be used with any of the other builder methods and still get validated data, like replace.

Parameters

mixed $key
string $value
boolean|null $escape

Returns

$this

save()

save(array|object  $data) : boolean

A convenience method that will attempt to determine whether the data should be inserted or updated. Will work with either an array or object. When using with custom class objects, you must ensure that the class will provide access to the class variables, even if through a magic method.

Parameters

array|object $data

Throws

\ReflectionException

Returns

boolean

classToArray()

classToArray(string|object  $data, string|null  $primaryKey = null, string  $dateFormat = 'datetime', boolean  $onlyChanged = true) : array

Takes a class an returns an array of it's public and protected properties as an array suitable for use in creates and updates.

Parameters

string|object $data
string|null $primaryKey
string $dateFormat
boolean $onlyChanged

Throws

\ReflectionException

Returns

array

getInsertID()

getInsertID() : integer

Returns last insert ID or 0.

Returns

integer

insert()

insert(array|object  $data = null, boolean  $returnID = true) : integer|string|boolean

Inserts data into the current table. If an object is provided, it will attempt to convert it to an array.

Parameters

array|object $data
boolean $returnID

Whether insert ID should be returned or not.

Throws

\ReflectionException

Returns

integer|string|boolean

insertBatch()

insertBatch(array  $set = null, boolean  $escape = null, integer  $batchSize = 100, boolean  $testing = false) : integer|boolean

Compiles batch insert strings and runs the queries, validating each row prior.

Parameters

array $set

An associative array of insert values

boolean $escape

Whether to escape values and identifiers

integer $batchSize
boolean $testing

Returns

integer|boolean —

Number of rows inserted or FALSE on failure

update()

update(integer|array|string  $id = null, array|object  $data = null) : boolean

Updates a single record in $this->table. If an object is provided, it will attempt to convert it into an array.

Parameters

integer|array|string $id
array|object $data

Throws

\ReflectionException

Returns

boolean

updateBatch()

updateBatch(array  $set = null, string  $index = null, integer  $batchSize = 100, boolean  $returnSQL = false) : mixed

Update_Batch

Compiles an update string and runs the query

Parameters

array $set

An associative array of update values

string $index

The where key

integer $batchSize

The size of the batch to run

boolean $returnSQL

True means SQL is returned, false will execute the query

Throws

\CodeIgniter\Database\Exceptions\DatabaseException

Returns

mixed —

Number of rows affected or FALSE on failure

delete()

delete(integer|array|null  $id = null, boolean  $purge = false) : mixed

Deletes a single record from $this->table where $id matches the table's primaryKey

Parameters

integer|array|null $id

The rows primary key(s)

boolean $purge

Allows overriding the soft deletes setting.

Throws

\CodeIgniter\Database\Exceptions\DatabaseException

Returns

mixed

purgeDeleted()

purgeDeleted() : boolean|mixed

Permanently deletes all rows that have been marked as deleted through soft deletes (deleted = 1)

Returns

boolean|mixed

withDeleted()

withDeleted(boolean  $val = true) : \CodeIgniter\Model

Sets $useSoftDeletes value so that we can temporarily override the softdeletes settings. Can be used for all find* methods.

Parameters

boolean $val

Returns

\CodeIgniter\Model

onlyDeleted()

onlyDeleted() : \CodeIgniter\Model

Works with the find* methods to return only the rows that have been deleted.

Returns

\CodeIgniter\Model

replace()

replace(null  $data = null, boolean  $returnSQL = false) : mixed

Replace

Compiles an replace into string and runs the query

Parameters

null $data
boolean $returnSQL

Returns

mixed

asArray()

asArray() : \CodeIgniter\Model

Sets the return type of the results to be as an associative array.

Returns

\CodeIgniter\Model

asObject()

asObject(string  $class = 'object') : \CodeIgniter\Model

Sets the return type to be of the specified type of object.

Defaults to a simple object, but can be any class that has class vars with the same name as the table columns, or at least allows them to be created.

Parameters

string $class

Returns

\CodeIgniter\Model

chunk()

chunk(integer  $size, \Closure  $userFunc) 

Loops over records in batches, allowing you to operate on them.

Works with $this->builder to get the Compiled select to determine the rows to operate on.

Parameters

integer $size
\Closure $userFunc

Throws

\CodeIgniter\Database\Exceptions\DataException

paginate()

paginate(integer  $perPage = 20, string  $group = 'default', integer  $page) : array|null

Works with $this->builder to get the Compiled Select to operate on.

Expects a GET variable (?page=2) that specifies the page of results to display.

Parameters

integer $perPage
string $group

Will be used by the pagination library to identify a unique pagination set.

integer $page

Optional page number (useful when the page number is provided in different way)

Returns

array|null

protect()

protect(boolean  $protect = true) : \CodeIgniter\Model

Sets whether or not we should whitelist data set during updates or inserts against $this->availableFields.

Parameters

boolean $protect

Returns

\CodeIgniter\Model

setTable()

setTable(string  $table) : \CodeIgniter\Model

Specify the table associated with a model

Parameters

string $table

Returns

\CodeIgniter\Model

errors()

errors(boolean  $forceDB = false) : array|null

Grabs the last error(s) that occurred. If data was validated, it will first check for errors there, otherwise will try to grab the last error from the Database connection.

Parameters

boolean $forceDB

Always grab the db error, not validation

Returns

array|null

skipValidation()

skipValidation(boolean  $skip = true) : \CodeIgniter\Model

Set the value of the skipValidation flag.

Parameters

boolean $skip

Returns

\CodeIgniter\Model

setValidationMessages()

setValidationMessages(array  $validationMessages) : void

Allows to set validation messages.

It could be used when you have to change default or override current validate messages.

Parameters

array $validationMessages

setValidationMessage()

setValidationMessage(string  $field, array  $fieldMessages) : void

Allows to set field wise validation message.

It could be used when you have to change default or override current validate messages.

Parameters

string $field
array $fieldMessages

validate()

validate(array|object  $data) : boolean

Validate the data against the validation rules (or the validation group) specified in the class property, $validationRules.

Parameters

array|object $data

Returns

boolean

getValidationRules()

getValidationRules(array  $options = array()) : array

Returns the model's defined validation rules so that they can be used elsewhere, if needed.

Parameters

array $options

Returns

array

getValidationMessages()

getValidationMessages() : array

Returns the model's define validation messages so they can be used elsewhere, if needed.

Returns

array

countAllResults()

countAllResults(boolean  $reset = true, boolean  $test = false) : mixed

Override countAllResults to account for soft deleted accounts.

Parameters

boolean $reset
boolean $test

Returns

mixed

__get()

__get(string  $name) : mixed

Provides/instantiates the builder/db connection and model's table/primary key names and return type.

Parameters

string $name

Returns

mixed

__isset()

__isset(string  $name) : boolean

Checks for the existence of properties across this model, builder, and db connection.

Parameters

string $name

Returns

boolean

__call()

__call(string  $name, array  $params) : \CodeIgniter\Model|null

Provides direct access to method in the builder (if available) and the database connection.

Parameters

string $name
array $params

Returns

\CodeIgniter\Model|null

builder()

builder(string  $table = null) : \CodeIgniter\Database\BaseBuilder

Provides a shared instance of the Query Builder.

Parameters

string $table

Throws

\CodeIgniter\Exceptions\ModelException;

Returns

\CodeIgniter\Database\BaseBuilder

doProtectFields()

doProtectFields(array  $data) : array

Ensures that only the fields that are allowed to be updated are in the data array.

Used by insert() and update() to protect against mass assignment vulnerabilities.

Parameters

array $data

Throws

\CodeIgniter\Database\Exceptions\DataException

Returns

array

setDate()

setDate(integer  $userData = null) : mixed

A utility function to allow child models to use the type of date/time format that they prefer. This is primarily used for setting created_at, updated_at and deleted_at values, but can be used by inheriting classes.

The available time formats are:

  • 'int' - Stores the date as an integer timestamp
  • 'datetime' - Stores the data in the SQL datetime format
  • 'date' - Stores the date (only) in the SQL date format.

Parameters

integer $userData

An optional PHP timestamp to be converted.

Throws

\CodeIgniter\Exceptions\ModelException;

Returns

mixed

cleanValidationRules()

cleanValidationRules(array  $rules, array|null  $data = null) : array

Removes any rules that apply to fields that have not been set currently so that rules don't block updating when only updating a partial row.

Parameters

array $rules
array|null $data

Returns

array

fillPlaceholders()

fillPlaceholders(array  $rules, array  $data) : array

Replace any placeholders within the rules with the values that match the 'key' of any properties being set. For example, if we had the following $data array:

[ 'id' => 13 ]

and the following rule:

'required|is_unique[users,email,id,{id}]'

The value of {id} would be replaced with the actual id in the form data:

'required|is_unique[users,email,id,13]'

Parameters

array $rules
array $data

Returns

array

trigger()

trigger(string  $event, array  $data) : mixed

A simple event trigger for Model Events that allows additional data manipulation within the model. Specifically intended for usage by child models this can be used to format data, save/load related classes, etc.

It is the responsibility of the callback methods to return the data itself.

Each $data array MUST have a 'data' key with the relevant data for callback methods (like an array of key/value pairs to insert or update, an array of results, etc)

Parameters

string $event
array $data

Throws

\CodeIgniter\Database\Exceptions\DataException

Returns

mixed