Model

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
package

CodeIgniter

mixin

BaseBuilder

Methods

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

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

Arguments

$name

string

$params

array

Response

\CodeIgniter\Model|null

Model constructor.

__construct(\CodeIgniter\Database\ConnectionInterface &$db = null, \CodeIgniter\Validation\ValidationInterface $validation = null) 

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

__get(string $name) : mixed

Arguments

$name

string

Response

mixed

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

__isset(string $name) : boolean

Arguments

$name

string

Response

boolean

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

asArray() : \CodeIgniter\Model

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

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

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.

Arguments

$class

string

Response

\CodeIgniter\Model

Provides a shared instance of the Query Builder.

builder(string $table = null) : \CodeIgniter\Database\BaseBuilder
Throws
\CodeIgniter\Exceptions\ModelException;

Arguments

$table

string

Response

\CodeIgniter\Database\BaseBuilder

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

chunk(integer $size, \Closure $userFunc) 

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

Throws
\CodeIgniter\Database\Exceptions\DataException

Arguments

$size

integer

$userFunc

\Closure

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

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

Arguments

$data

string|object

$primaryKey

string|null

$dateFormat

string

$onlyChanged

boolean

Response

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.

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

Arguments

$rules

array

$data

array|null

Response

array

Override countAllResults to account for soft deleted accounts.

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

Arguments

$reset

boolean

$test

boolean

Response

mixed

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

delete(integer|array|null $id = null, boolean $purge = false) : mixed
Throws
\CodeIgniter\Database\Exceptions\DatabaseException

Arguments

$id

integer|array|null

The rows primary key(s)

$purge

boolean

Allows overriding the soft deletes setting.

Response

mixed

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

doProtectFields(array $data) : array

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

Throws
\CodeIgniter\Database\Exceptions\DataException

Arguments

$data

array

Response

array

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.

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

Arguments

$forceDB

boolean

Always grab the db error, not validation

Response

array|null

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:

fillPlaceholders(array $rules, array $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]'

Arguments

$rules

array

$data

array

Response

array

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

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

Arguments

$id

mixed|array|null

One primary key or an array of primary keys

Response

array|object|null

The resulting row of data, or null.

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

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

Arguments

$limit

integer

$offset

integer

Response

array|null

Fetches the column of database from $this->table

findColumn(string $columnName) : array|null
Throws
\CodeIgniter\Database\Exceptions\DataException

Arguments

$columnName

string

Response

array|null

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

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

first() : array|object|null

Response

array|object|null

Returns last insert ID or 0.

getInsertID() : integer

Response

integer

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

getValidationMessages() : array

Response

array

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

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

Arguments

$options

array

Response

array

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

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

Arguments

$data

array|object

$returnID

boolean

Whether insert ID should be returned or not.

Response

integer|string|boolean

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

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

Arguments

$set

array

An associative array of insert values

$escape

boolean

Whether to escape values and identifiers

$batchSize

integer

$testing

boolean

Response

integer|boolean

Number of rows inserted or FALSE on failure

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

onlyDeleted() : \CodeIgniter\Model

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

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

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

Arguments

$perPage

integer

$group

string

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

$page

integer

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

Response

array|null

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

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

Arguments

$protect

boolean

Response

\CodeIgniter\Model

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

purgeDeleted() : boolean|mixed

Response

boolean|mixed

Replace

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

Compiles an replace into string and runs the query

Arguments

$data

null

$returnSQL

boolean

Response

mixed

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.

save(array|object $data) : boolean
Throws
\ReflectionException

Arguments

$data

array|object

Response

boolean

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.

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

Arguments

$key

mixed

$value

string

$escape

boolean|null

Response

$this

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.

setDate(integer $userData = null) : mixed

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.
Throws
\CodeIgniter\Exceptions\ModelException;

Arguments

$userData

integer

An optional PHP timestamp to be converted.

Response

mixed

Specify the table associated with a model

setTable(string $table) : \CodeIgniter\Model

Arguments

$table

string

Response

\CodeIgniter\Model

Allows to set field wise validation message.

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

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

Arguments

$field

string

$fieldMessages

array

Allows to set validation messages.

setValidationMessages(array $validationMessages) : void

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

Arguments

$validationMessages

array

Set the value of the skipValidation flag.

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

Arguments

$skip

boolean

Response

\CodeIgniter\Model

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.

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

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)

Throws
\CodeIgniter\Database\Exceptions\DataException

Arguments

$event

string

$data

array

Response

mixed

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

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

Arguments

$id

integer|array|string

$data

array|object

Response

boolean

Update_Batch

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

Compiles an update string and runs the query

Throws
\CodeIgniter\Database\Exceptions\DatabaseException

Arguments

$set

array

An associative array of update values

$index

string

The where key

$batchSize

integer

The size of the batch to run

$returnSQL

boolean

True means SQL is returned, false will execute the query

Response

mixed

Number of rows affected or FALSE on failure

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

validate(array|object $data) : boolean

Arguments

$data

array|object

Response

boolean

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

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

Arguments

$val

boolean

Response

\CodeIgniter\Model

Properties

Pager instance.

pager : \CodeIgniter\Pager\Pager

Populated after calling $this->paginate()

var

Type(s)

\CodeIgniter\Pager\Pager

Name of database table

table : string
var

Type(s)

string

The table's primary key.

primaryKey : string
var

Type(s)

string

Last insert ID

insertID : integer
var

Type(s)

integer

The Database connection group that should be instantiated.

DBGroup : string
var

Type(s)

string

The format that the results should be returned as.

returnType : string

Will be overridden if the as* methods are used.

var

Type(s)

string

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

useSoftDeletes : boolean
var

Type(s)

boolean

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

allowedFields : array
var

Type(s)

array

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

useTimestamps : boolean
var

Type(s)

boolean

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

dateFormat : string

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

var

Type(s)

string

The column used for insert timestamps

createdField : string
var

Type(s)

string

The column used for update timestamps

updatedField : string
var

Type(s)

string

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

tempUseSoftDeletes : boolean
var

Type(s)

boolean

The column used to save soft delete state

deletedField : string
var

Type(s)

string

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

tempReturnType : string
var

Type(s)

string

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

protectFields : boolean
var

Type(s)

boolean

Database Connection

db : \CodeIgniter\Database\ConnectionInterface

Query Builder object

builder : \CodeIgniter\Database\BaseBuilder
var

Type(s)

\CodeIgniter\Database\BaseBuilder

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

validationRules : array

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

var

Type(s)

array

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

validationMessages : array
var

Type(s)

array

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

skipValidation : boolean
var

Type(s)

boolean

Our validator instance.

validation : \CodeIgniter\Validation\Validation

Callbacks for beforeInsert

beforeInsert : \CodeIgniter\type
var

Type(s)

\CodeIgniter\type

Callbacks for afterInsert

afterInsert : \CodeIgniter\type
var

Type(s)

\CodeIgniter\type

Callbacks for beforeUpdate

beforeUpdate : \CodeIgniter\type
var

Type(s)

\CodeIgniter\type

Callbacks for afterUpdate

afterUpdate : \CodeIgniter\type
var

Type(s)

\CodeIgniter\type

Callbacks for afterFind

afterFind : \CodeIgniter\type
var

Type(s)

\CodeIgniter\type

Callbacks for beforeDelete

beforeDelete : \CodeIgniter\type
var

Type(s)

\CodeIgniter\type

Callbacks for afterDelete

afterDelete : \CodeIgniter\type
var

Type(s)

\CodeIgniter\type

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

tempData : array
var

Type(s)

array