CodeIgniter v4.7 API

Model extends BaseModel
in package

The Model class extends BaseModel and provides additional convenient features that makes working with a SQL database table less painful.

It will:

  • automatically connect to database
  • allow intermingling calls to the builder
  • removes the need to use Result object directly in most cases
Tags
phpstan-import-type

row_array from BaseModel

Table of Contents

Properties

$db  : BaseConnection
Database Connection.
$pager  : Pager
Pager instance.
$afterDelete  : array<int, string>
Callbacks for "afterDelete" event.
$afterFind  : array<int, string>
Callbacks for "afterFind" event.
$afterInsert  : array<int, string>
Callbacks for "afterInsert" event.
$afterInsertBatch  : array<int, string>
Callbacks for "afterInsertBatch" event.
$afterUpdate  : array<int, string>
Callbacks for "afterUpdate" event.
$afterUpdateBatch  : array<int, string>
Callbacks for "afterUpdateBatch" event.
$allowCallbacks  : bool
Whether to trigger the defined callbacks.
$allowedFields  : array<int, string>
An array of field names that are allowed to be set by the user in inserts/updates.
$allowEmptyInserts  : bool
Whether to allow inserting empty data.
$beforeDelete  : array<int, string>
Callbacks for "beforeDelete" event.
$beforeFind  : array<int, string>
Callbacks for "beforeFind" event.
$beforeInsert  : array<int, string>
Callbacks for "beforeInsert" event.
$beforeInsertBatch  : array<int, string>
Callbacks for "beforeInsertBatch" event.
$beforeUpdate  : array<int, string>
Callbacks for "beforeUpdate" event.
$beforeUpdateBatch  : array<int, string>
Callbacks for "beforeUpdateBatch" event.
$builder  : BaseBuilder|null
Query Builder object.
$castHandlers  : array<string|int, mixed>
Custom convert handlers.
$casts  : array<string, string>
Array of column names and the type of value to cast.
$cleanValidationRules  : bool
Whether rules should be removed that do not exist in the passed data. Used in updates.
$converter  : DataConverter|null
$createdField  : string
The column used for insert timestamps.
$dateFormat  : "date"|"datetime"|"int"
The type of column that created_at and updated_at are expected to.
$DBGroup  : non-empty-string|null
The Database connection group that should be instantiated.
$deletedField  : string
The column used to save soft delete state.
$escape  : array<int|string, bool|null>
Escape array that maps usage of escape flag for every parameter.
$insertID  : int|string
Last insert ID.
$primaryKey  : string
The table's primary key.
$protectFields  : bool
Determines whether the model should protect field names during mass assignment operations such as $this->insert(), $this->update().
$returnType  : "array"|"object"|class-string
The format that the results should be returned as.
$skipValidation  : bool
Skip the model's validation.
$table  : string
Name of database table.
$tempAllowCallbacks  : bool
Used by $this->allowCallbacks() to override the model's $allowCallbacks setting.
$tempData  : row_array}|array{}
Holds information passed in via 'set' so that we can capture it (not the builder) and ensure it gets validated first.
$tempReturnType  : "array"|"object"|class-string
The temporary format of the result.
$tempUseSoftDeletes  : bool
Used by $this->withDeleted() to override the model's "softDelete" setting.
$updatedField  : string
The column used for update timestamps.
$updateOnlyChanged  : bool
Whether to update Entity's only changed data.
$useAutoIncrement  : bool
Whether primary key uses auto increment.
$useSoftDeletes  : bool
If this model should use "softDeletes" and simply set a date when rows are deleted, or do hard deletes.
$useTimestamps  : bool
If true, will set created_at, and updated_at values during insert and update routines.
$validation  : ValidationInterface|null
Our validator instance.
$validationMessages  : array<string, array<string, string>>
Contains any custom error messages to be used during data validation.
$validationRules  : array<string, array<string, array<string, string>|string>|string>|string
Rules used to validate data in insert(), update(), save(), insertBatch(), and updateBatch() methods.
$builderMethodsNotAvailable  : array<int, string>
Builder method names that should not be used in the Model.

Methods

__call()  : $this|array<int|string, mixed>|BaseBuilder|bool|float|int|object|string|null
Provides direct access to method in the builder (if available) and the database connection.
__construct()  : mixed
__get()  : array<int|string, mixed>|BaseBuilder|bool|float|int|object|string|null
Provides/instantiates the builder/db connection and model's table/primary key names and return type.
__isset()  : bool
Checks for the existence of properties across this model, builder, and db connection.
allowCallbacks()  : $this
Sets $tempAllowCallbacks value so that we can temporarily override the setting. Resets after the next method that uses triggers.
allowEmptyInserts()  : self
Sets $allowEmptyInserts.
asArray()  : $this
Sets the return type of the results to be as an associative array.
asObject()  : $this
Sets the return type to be of the specified type of object.
builder()  : BaseBuilder
Provides a shared instance of the Query Builder.
chunk()  : void
Loops over records in batches, allowing you to operate on them.
cleanRules()  : $this
Should validation rules be removed before saving? Most handy when doing updates.
countAllResults()  : int|string
Override countAllResults to account for soft deleted accounts.
delete()  : bool|string
Deletes a single record from the database where $id matches.
errors()  : array<string, string>
Grabs the last error(s) that occurred.
find()  : row_array>)
Fetches the row of database.
findAll()  : array<int, object|row_array>
Fetches all results, while optionally limiting them.
findColumn()  : array<int, bool|float|int|array<int, mixed>|object|string|null>|null
Fetches the column of database.
first()  : object|row_array|null
Returns the first row of the result set.
getIdValue()  : int|string|null
Public getter to return the ID value for the data array or object.
getInsertID()  : int|string
Returns last insert ID or 0.
getValidationMessages()  : array<string, array<string, string>>
Returns the model's validation messages, so they can be used elsewhere, if needed.
getValidationRules()  : array<string, array<string, array<string, string>|string>|string>
Returns the model's defined validation rules so that they can be used elsewhere, if needed.
groupBy()  : $this
groupEnd()  : $this
groupStart()  : $this
having()  : $this
havingGroupEnd()  : $this
havingGroupStart()  : $this
havingIn()  : $this
havingLike()  : $this
havingNotIn()  : $this
insert()  : ($returnID is true ? false|int|string : bool)
Inserts data into the database. If an object is provided, it will attempt to convert it to an array.
insertBatch()  : false|int|array<int, string>
Compiles batch insert runs the queries, validating each row prior.
join()  : $this
like()  : $this
limit()  : $this
notGroupStart()  : $this
notHavingGroupStart()  : $this
notHavingLike()  : $this
notLike()  : $this
offset()  : $this
onlyDeleted()  : $this
Works with the $this->find* methods to return only the rows that have been deleted.
orderBy()  : $this
orGroupStart()  : $this
orHaving()  : $this
orHavingGroupStart()  : $this
orHavingIn()  : $this
orHavingLike()  : $this
orHavingNotIn()  : $this
orLike()  : $this
orNotGroupStart()  : $this
orNotHavingGroupStart()  : $this
orNotHavingLike()  : $this
orNotLike()  : $this
orWhere()  : $this
orWhereIn()  : $this
orWhereNotIn()  : $this
paginate()  : array<int, object|row_array>
Works with Pager to get the size and offset parameters.
protect()  : $this
Sets whether or not we should whitelist data set during updates or inserts against $this->availableFields.
purgeDeleted()  : bool|string
Permanently deletes all rows that have been marked as deleted through soft deletes (value of column $deletedField is not null).
replace()  : BaseResult|false|Query|string
Compiles a replace and runs the query.
save()  : bool
A convenience method that will attempt to determine whether the data should be inserted or updated.
select()  : $this
selectAvg()  : $this
selectCount()  : $this
selectMax()  : $this
selectMin()  : $this
selectSum()  : $this
set()  : $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.
setAllowedFields()  : $this
It could be used when you have to change default or override current allowed fields.
setTable()  : $this
Specify the table associated with a model.
setValidationMessage()  : $this
Allows to set field wise validation message.
setValidationMessages()  : $this
Allows to set (and reset) validation messages.
setValidationRule()  : $this
Allows to set field wise validation rules.
setValidationRules()  : $this
Allows to set (and reset) validation rules.
skipValidation()  : $this
Set the value of the $skipValidation flag.
update()  : bool
Updates a single record in the database. If an object is provided, it will attempt to convert it into an array.
updateBatch()  : false|int|array<int, string>
Compiles an update and runs the query.
validate()  : bool
Validate the row data against the validation rules (or the validation group) specified in the class property, $validationRules.
when()  : $this
whenNot()  : $this
where()  : $this
whereIn()  : $this
whereNotIn()  : $this
withDeleted()  : $this
Sets $useSoftDeletes value so that we can temporarily override the soft deletes settings. Can be used for all find* methods.
cleanValidationRules()  : array<string, array<string, array<string, string>|string>|string>
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.
convertToReturnType()  : array<string, mixed>|object
Converts database data array to return type value.
createDataConverter()  : void
Creates DataConverter instance.
doDelete()  : bool|string
Deletes a single record from the database where $id matches the table's primary key.
doErrors()  : array<string, string>
Grabs the last error(s) that occurred from the Database connection.
doFind()  : row_array>)
Fetches the row(s) of database with a primary key matching $id.
doFindAll()  : array<int, object|row_array>
Fetches all results, while optionally limiting them.
doFindColumn()  : array<int, row_array>|null
Fetches the column of database.
doFirst()  : object|row_array|null
Returns the first row of the result set.
doInsert()  : bool
Inserts data into the current database.
doInsertBatch()  : false|int|array<int, string>
Compiles batch insert and runs the queries, validating each row prior.
doOnlyDeleted()  : void
Works with the $this->find* methods to return only the rows that have been deleted (value of column $deletedField is not null).
doProtectFields()  : row_array
Ensures that only the fields that are allowed to be updated are in the data array.
doProtectFieldsForInsert()  : row_array
Ensures that only the fields that are allowed to be inserted are in the data array.
doPurgeDeleted()  : bool|string
Permanently deletes all rows that have been marked as deleted through soft deletes (value of column $deletedField is not null).
doReplace()  : BaseResult|false|Query|string
Compiles a replace and runs the query.
doUpdate()  : bool
Updates a single record in the database.
doUpdateBatch()  : false|int|array<int, string>
Compiles an update and runs the query.
ensureValidation()  : void
initialize()  : void
Initializes the instance with any additional steps.
intToDate()  : int|string
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.
objectToArray()  : array<string, mixed>
Takes a class and returns an array of its public and protected properties as an array suitable for use in creates and updates.
objectToRawArray()  : array<string, mixed>
Takes a class and returns an array of its public and protected properties as an array with raw values.
setCreatedField()  : row_array
Set datetime to created field.
setDate()  : int|string
Sets the timestamp or current timestamp if null value is passed.
setUpdatedField()  : row_array
Set datetime to updated field.
shouldUpdate()  : bool
This method is called on save to determine if entry have to be updated.
timeToDate()  : int|string
Converts Time value to string using $this->dateFormat.
timeToString()  : array<string, mixed>
Convert any Time instances to appropriate $dateFormat.
transformDataToArray()  : array<int|string, mixed>
Transform data to array.
trigger()  : TEventData
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.
useCasts()  : bool
Are casts used?
validateID()  : void
Validates that the primary key values are valid for update/delete/insert operations.
checkBuilderMethod()  : void
Checks the Builder method name that should not be used in the Model.

Properties

$pager

Pager instance.

public Pager $pager

Populated after calling $this->paginate().

$afterDelete

Callbacks for "afterDelete" event.

protected array<int, string> $afterDelete = []

$afterFind

Callbacks for "afterFind" event.

protected array<int, string> $afterFind = []

$afterInsert

Callbacks for "afterInsert" event.

protected array<int, string> $afterInsert = []

$afterInsertBatch

Callbacks for "afterInsertBatch" event.

protected array<int, string> $afterInsertBatch = []

$afterUpdate

Callbacks for "afterUpdate" event.

protected array<int, string> $afterUpdate = []

$afterUpdateBatch

Callbacks for "afterUpdateBatch" event.

protected array<int, string> $afterUpdateBatch = []

$allowCallbacks

Whether to trigger the defined callbacks.

protected bool $allowCallbacks = true

$allowedFields

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

protected array<int, string> $allowedFields = []

$allowEmptyInserts

Whether to allow inserting empty data.

protected bool $allowEmptyInserts = false

$beforeDelete

Callbacks for "beforeDelete" event.

protected array<int, string> $beforeDelete = []

$beforeFind

Callbacks for "beforeFind" event.

protected array<int, string> $beforeFind = []

$beforeInsert

Callbacks for "beforeInsert" event.

protected array<int, string> $beforeInsert = []

$beforeInsertBatch

Callbacks for "beforeInsertBatch" event.

protected array<int, string> $beforeInsertBatch = []

$beforeUpdate

Callbacks for "beforeUpdate" event.

protected array<int, string> $beforeUpdate = []

$beforeUpdateBatch

Callbacks for "beforeUpdateBatch" event.

protected array<int, string> $beforeUpdateBatch = []

$castHandlers

Custom convert handlers.

protected array<string|int, mixed> $castHandlers = []

$casts

Array of column names and the type of value to cast.

protected array<string, string> $casts = []

Array order ['column' => 'type'].

$cleanValidationRules

Whether rules should be removed that do not exist in the passed data. Used in updates.

protected bool $cleanValidationRules = true

$createdField

The column used for insert timestamps.

protected string $createdField = 'created_at'

$dateFormat

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

protected "date"|"datetime"|"int" $dateFormat = 'datetime'

$DBGroup

The Database connection group that should be instantiated.

protected non-empty-string|null $DBGroup

$deletedField

The column used to save soft delete state.

protected string $deletedField = 'deleted_at'

$escape

Escape array that maps usage of escape flag for every parameter.

protected array<int|string, bool|null> $escape = []

$insertID

Last insert ID.

protected int|string $insertID = 0

$primaryKey

The table's primary key.

protected string $primaryKey = 'id'

$protectFields

Determines whether the model should protect field names during mass assignment operations such as $this->insert(), $this->update().

protected bool $protectFields = true

When set to true, only the fields explicitly defined in the $allowedFields property will be allowed for mass assignment. This helps prevent unintended modification of database fields and improves security by avoiding mass assignment vulnerabilities.

$returnType

The format that the results should be returned as.

protected "array"|"object"|class-string $returnType = 'array'

Will be overridden if the $this->asArray(), $this->asObject() methods are used.

$skipValidation

Skip the model's validation.

protected bool $skipValidation = false

Used in conjunction with $this->skipValidation() to skip data validation for any future calls.

$table

Name of database table.

protected string $table

$tempAllowCallbacks

Used by $this->allowCallbacks() to override the model's $allowCallbacks setting.

protected bool $tempAllowCallbacks

$tempData

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

protected row_array}|array{} $tempData = []

$tempReturnType

The temporary format of the result.

protected "array"|"object"|class-string $tempReturnType

Used by $this->asArray() and $this->asObject() to provide temporary overrides of model default.

$tempUseSoftDeletes

Used by $this->withDeleted() to override the model's "softDelete" setting.

protected bool $tempUseSoftDeletes

$updatedField

The column used for update timestamps.

protected string $updatedField = 'updated_at'

$updateOnlyChanged

Whether to update Entity's only changed data.

protected bool $updateOnlyChanged = true

$useAutoIncrement

Whether primary key uses auto increment.

protected bool $useAutoIncrement = true

$useSoftDeletes

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

protected bool $useSoftDeletes = false

$useTimestamps

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

protected bool $useTimestamps = false

$validationMessages

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

protected array<string, array<string, string>> $validationMessages = []

The column is used as the keys.

$builderMethodsNotAvailable

Builder method names that should not be used in the Model.

private array<int, string> $builderMethodsNotAvailable = ['getCompiledInsert', 'getCompiledSelect', 'getCompiledUpdate']

Methods

__call()

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

public __call(string $name, array<string|int, mixed> $params) : $this|array<int|string, mixed>|BaseBuilder|bool|float|int|object|string|null
Parameters
$name : string
$params : array<string|int, mixed>
Return values
$this|array<int|string, mixed>|BaseBuilder|bool|float|int|object|string|null

__get()

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

public __get(string $name) : array<int|string, mixed>|BaseBuilder|bool|float|int|object|string|null
Parameters
$name : string
Return values
array<int|string, mixed>|BaseBuilder|bool|float|int|object|string|null

__isset()

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

public __isset(string $name) : bool
Parameters
$name : string
Return values
bool

allowCallbacks()

Sets $tempAllowCallbacks value so that we can temporarily override the setting. Resets after the next method that uses triggers.

public allowCallbacks([bool $val = true ]) : $this
Parameters
$val : bool = true
Return values
$this

allowEmptyInserts()

Sets $allowEmptyInserts.

public allowEmptyInserts([bool $value = true ]) : self
Parameters
$value : bool = true
Return values
self

asArray()

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

public asArray() : $this
Return values
$this

asObject()

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

public asObject(["object"|class-string $class = 'object' ]) : $this

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

Parameters
$class : "object"|class-string = 'object'
Return values
$this

builder()

Provides a shared instance of the Query Builder.

public builder([non-empty-string|null $table = null ]) : BaseBuilder
Parameters
$table : non-empty-string|null = null
Tags
throws
ModelException
Return values
BaseBuilder

chunk()

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

public chunk(int $size, Closure $userFunc) : void

Works with $this->builder to get the Compiled select to determine the rows to operate on. This method works only with dbCalls.

Parameters
$size : int
$userFunc : Closure

cleanRules()

Should validation rules be removed before saving? Most handy when doing updates.

public cleanRules([bool $choice = false ]) : $this
Parameters
$choice : bool = false
Return values
$this

countAllResults()

Override countAllResults to account for soft deleted accounts.

public countAllResults([bool $reset = true ][, bool $test = false ]) : int|string

This method works only with DB calls.

Parameters
$reset : bool = true

When false, the $tempUseSoftDeletes will be dependent on $useSoftDeletes value because we don't want to add the same "where" condition for the second time.

$test : bool = false

true returns the number of all records, false will execute the query.

Return values
int|string

Returns a SQL string if in test mode.

delete()

Deletes a single record from the database where $id matches.

public delete([int|array<int, int|string>|RawSql|string|null $id = null ][, bool $purge = false ]) : bool|string
Parameters
$id : int|array<int, int|string>|RawSql|string|null = null

The rows primary key(s).

$purge : bool = false

Allows overriding the soft deletes setting.

Tags
throws
DatabaseException
Return values
bool|string

Returns a SQL string if in test mode.

errors()

Grabs the last error(s) that occurred.

public errors([bool $forceDB = false ]) : array<string, string>

If data was validated, it will first check for errors there, otherwise will try to grab the last error from the Database connection.

The return array should be in the following format: ['source' => 'message'].

Parameters
$forceDB : bool = false

Always grab the DB error, not validation.

Return values
array<string, string>

find()

Fetches the row of database.

public find([int|array<int, int|string>|string|null $id = null ]) : row_array>)
Parameters
$id : int|array<int, int|string>|string|null = null

One primary key or an array of primary keys.

Return values
row_array>)

findAll()

Fetches all results, while optionally limiting them.

public findAll([int|null $limit = null ][, int $offset = 0 ]) : array<int, object|row_array>
Parameters
$limit : int|null = null
$offset : int = 0
Return values
array<int, object|row_array>

findColumn()

Fetches the column of database.

public findColumn(string $columnName) : array<int, bool|float|int|array<int, mixed>|object|string|null>|null
Parameters
$columnName : string
Tags
throws
DataException
Return values
array<int, bool|float|int|array<int, mixed>|object|string|null>|null

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

first()

Returns the first row of the result set.

public first() : object|row_array|null
Return values
object|row_array|null

getIdValue()

Public getter to return the ID value for the data array or object.

public getIdValue(mixed $row) : int|string|null

For example with SQL this will return $data->{$this->primaryKey}.

Parameters
$row : mixed
Return values
int|string|null

getInsertID()

Returns last insert ID or 0.

public getInsertID() : int|string
Return values
int|string

getValidationMessages()

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

public getValidationMessages() : array<string, array<string, string>>
Return values
array<string, array<string, string>>

getValidationRules()

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

public getValidationRules([array{only?: list, except?: list$options = [] ]) : array<string, array<string, array<string, string>|string>|string>
Parameters
$options : array{only?: list, except?: list} = []

Filter the list of rules

Return values
array<string, array<string, array<string, string>|string>|string>

groupBy()

public groupBy(mixed $by[, bool|null $escape = = 'null' ]) : $this
Parameters
$by : mixed
$escape : bool|null = = 'null'
Return values
$this

groupEnd()

public groupEnd() : $this
Return values
$this

groupStart()

public groupStart() : $this
Return values
$this

having()

public having(mixed $key[, mixed $value = = 'null' ][, bool|null $escape = = 'null' ]) : $this
Parameters
$key : mixed
$value : mixed = = 'null'
$escape : bool|null = = 'null'
Return values
$this

havingGroupEnd()

public havingGroupEnd() : $this
Return values
$this

havingGroupStart()

public havingGroupStart() : $this
Return values
$this

havingIn()

public havingIn([string|null $key = = 'null' ][, mixed $values = = 'null' ][, bool|null $escape = = 'null' ]) : $this
Parameters
$key : string|null = = 'null'
$values : mixed = = 'null'
$escape : bool|null = = 'null'
Return values
$this

havingLike()

public havingLike(mixed $field[, string $match = = '\'\'' ][, string $side = = '\'both\'' ][, bool|null $escape = = 'null' ][, bool $insensitiveSearch = = 'false' ]) : $this
Parameters
$field : mixed
$match : string = = '\'\''
$side : string = = '\'both\''
$escape : bool|null = = 'null'
$insensitiveSearch : bool = = 'false'
Return values
$this

havingNotIn()

public havingNotIn([string|null $key = = 'null' ][, mixed $values = = 'null' ][, bool|null $escape = = 'null' ]) : $this
Parameters
$key : string|null = = 'null'
$values : mixed = = 'null'
$escape : bool|null = = 'null'
Return values
$this

insert()

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

public insert([mixed $row = null ][, bool $returnID = true ]) : ($returnID is true ? false|int|string : bool)
Parameters
$row : mixed = null
$returnID : bool = true

Whether insert ID should be returned or not.

Return values
($returnID is true ? false|int|string : bool)

insertBatch()

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

public insertBatch([array<int, object|row_array>|null $set = null ][, bool|null $escape = null ][, int $batchSize = 100 ][, bool $testing = false ]) : false|int|array<int, string>
Parameters
$set : array<int, object|row_array>|null = null

An associative array of insert values.

$escape : bool|null = null

Whether to escape values.

$batchSize : int = 100

The size of the batch to run.

$testing : bool = false

true means only number of records is returned, false will execute the query.

Tags
throws
ReflectionException
Return values
false|int|array<int, string>

Number of rows inserted or false on failure.

join()

public join(string $table, string $cond[, string $type = = '\'\'' ][, bool|null $escape = = 'null' ]) : $this
Parameters
$table : string
$cond : string
$type : string = = '\'\''
$escape : bool|null = = 'null'
Return values
$this

like()

public like(mixed $field[, string $match = = '\'\'' ][, string $side = = '\'both\'' ][, bool|null $escape = = 'null' ][, bool $insensitiveSearch = = 'false' ]) : $this
Parameters
$field : mixed
$match : string = = '\'\''
$side : string = = '\'both\''
$escape : bool|null = = 'null'
$insensitiveSearch : bool = = 'false'
Return values
$this

limit()

public limit([int|null $value = = 'null' ][, int|null $offset = = '0' ]) : $this
Parameters
$value : int|null = = 'null'
$offset : int|null = = '0'
Return values
$this

notGroupStart()

public notGroupStart() : $this
Return values
$this

notHavingGroupStart()

public notHavingGroupStart() : $this
Return values
$this

notHavingLike()

public notHavingLike(mixed $field[, string $match = = '\'\'' ][, string $side = = '\'both\'' ][, bool|null $escape = = 'null' ][, bool $insensitiveSearch = = 'false' ]) : $this
Parameters
$field : mixed
$match : string = = '\'\''
$side : string = = '\'both\''
$escape : bool|null = = 'null'
$insensitiveSearch : bool = = 'false'
Return values
$this

notLike()

public notLike(mixed $field[, string $match = = '\'\'' ][, string $side = = '\'both\'' ][, bool|null $escape = = 'null' ][, bool $insensitiveSearch = = 'false' ]) : $this
Parameters
$field : mixed
$match : string = = '\'\''
$side : string = = '\'both\''
$escape : bool|null = = 'null'
$insensitiveSearch : bool = = 'false'
Return values
$this

offset()

public offset(int $offset) : $this
Parameters
$offset : int
Return values
$this

onlyDeleted()

Works with the $this->find* methods to return only the rows that have been deleted.

public onlyDeleted() : $this
Return values
$this

orderBy()

public orderBy(string $orderBy[, string $direction = = '\'\'' ][, bool|null $escape = = 'null' ]) : $this
Parameters
$orderBy : string
$direction : string = = '\'\''
$escape : bool|null = = 'null'
Return values
$this

orGroupStart()

public orGroupStart() : $this
Return values
$this

orHaving()

public orHaving(mixed $key[, mixed $value = = 'null' ][, bool|null $escape = = 'null' ]) : $this
Parameters
$key : mixed
$value : mixed = = 'null'
$escape : bool|null = = 'null'
Return values
$this

orHavingGroupStart()

public orHavingGroupStart() : $this
Return values
$this

orHavingIn()

public orHavingIn([string|null $key = = 'null' ][, mixed $values = = 'null' ][, bool|null $escape = = 'null' ]) : $this
Parameters
$key : string|null = = 'null'
$values : mixed = = 'null'
$escape : bool|null = = 'null'
Return values
$this

orHavingLike()

public orHavingLike(mixed $field[, string $match = = '\'\'' ][, string $side = = '\'both\'' ][, bool|null $escape = = 'null' ][, bool $insensitiveSearch = = 'false' ]) : $this
Parameters
$field : mixed
$match : string = = '\'\''
$side : string = = '\'both\''
$escape : bool|null = = 'null'
$insensitiveSearch : bool = = 'false'
Return values
$this

orHavingNotIn()

public orHavingNotIn([string|null $key = = 'null' ][, mixed $values = = 'null' ][, bool|null $escape = = 'null' ]) : $this
Parameters
$key : string|null = = 'null'
$values : mixed = = 'null'
$escape : bool|null = = 'null'
Return values
$this

orLike()

public orLike(mixed $field[, string $match = = '\'\'' ][, string $side = = '\'both\'' ][, bool|null $escape = = 'null' ][, bool $insensitiveSearch = = 'false' ]) : $this
Parameters
$field : mixed
$match : string = = '\'\''
$side : string = = '\'both\''
$escape : bool|null = = 'null'
$insensitiveSearch : bool = = 'false'
Return values
$this

orNotGroupStart()

public orNotGroupStart() : $this
Return values
$this

orNotHavingGroupStart()

public orNotHavingGroupStart() : $this
Return values
$this

orNotHavingLike()

public orNotHavingLike(mixed $field[, string $match = = '\'\'' ][, string $side = = '\'both\'' ][, bool|null $escape = = 'null' ][, bool $insensitiveSearch = = 'false' ]) : $this
Parameters
$field : mixed
$match : string = = '\'\''
$side : string = = '\'both\''
$escape : bool|null = = 'null'
$insensitiveSearch : bool = = 'false'
Return values
$this

orNotLike()

public orNotLike(mixed $field[, string $match = = '\'\'' ][, string $side = = '\'both\'' ][, bool|null $escape = = 'null' ][, bool $insensitiveSearch = = 'false' ]) : $this
Parameters
$field : mixed
$match : string = = '\'\''
$side : string = = '\'both\''
$escape : bool|null = = 'null'
$insensitiveSearch : bool = = 'false'
Return values
$this

orWhere()

public orWhere(mixed $key[, mixed $value = = 'null' ][, bool|null $escape = = 'null' ]) : $this
Parameters
$key : mixed
$value : mixed = = 'null'
$escape : bool|null = = 'null'
Return values
$this

orWhereIn()

public orWhereIn([string|null $key = = 'null' ][, mixed $values = = 'null' ][, bool|null $escape = = 'null' ]) : $this
Parameters
$key : string|null = = 'null'
$values : mixed = = 'null'
$escape : bool|null = = 'null'
Return values
$this

orWhereNotIn()

public orWhereNotIn([string|null $key = = 'null' ][, mixed $values = = 'null' ][, bool|null $escape = = 'null' ]) : $this
Parameters
$key : string|null = = 'null'
$values : mixed = = 'null'
$escape : bool|null = = 'null'
Return values
$this

paginate()

Works with Pager to get the size and offset parameters.

public paginate([int|null $perPage = null ][, string $group = 'default' ][, int|null $page = null ][, int $segment = 0 ]) : array<int, object|row_array>

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

Parameters
$perPage : int|null = null

Items per page.

$group : string = 'default'

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

$page : int|null = null

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

$segment : int = 0

Optional URI segment number (if page number is provided by URI segment).

Return values
array<int, object|row_array>

protect()

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

public protect([bool $protect = true ]) : $this
Parameters
$protect : bool = true
Return values
$this

purgeDeleted()

Permanently deletes all rows that have been marked as deleted through soft deletes (value of column $deletedField is not null).

public purgeDeleted() : bool|string
Return values
bool|string

Returns a SQL string if in test mode.

replace()

Compiles a replace and runs the query.

public replace([row_array|null $row = null ][, bool $returnSQL = false ]) : BaseResult|false|Query|string
Parameters
$row : row_array|null = null
$returnSQL : bool = false

true means SQL is returned, false will execute the query.

Return values
BaseResult|false|Query|string

save()

A convenience method that will attempt to determine whether the data should be inserted or updated.

public save(object|row_array $row) : bool

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
$row : object|row_array
Tags
throws
ReflectionException
Return values
bool

select()

public select([mixed $select = = '\'*\'' ][, bool|null $escape = = 'null' ]) : $this
Parameters
$select : mixed = = '\'*\''
$escape : bool|null = = 'null'
Return values
$this

selectAvg()

public selectAvg([string $select = = '\'\'' ][, string $alias = = '\'\'' ]) : $this
Parameters
$select : string = = '\'\''
$alias : string = = '\'\''
Return values
$this

selectCount()

public selectCount([string $select = = '\'\'' ][, string $alias = = '\'\'' ]) : $this
Parameters
$select : string = = '\'\''
$alias : string = = '\'\''
Return values
$this

selectMax()

public selectMax([string $select = = '\'\'' ][, string $alias = = '\'\'' ]) : $this
Parameters
$select : string = = '\'\''
$alias : string = = '\'\''
Return values
$this

selectMin()

public selectMin([string $select = = '\'\'' ][, string $alias = = '\'\'' ]) : $this
Parameters
$select : string = = '\'\''
$alias : string = = '\'\''
Return values
$this

selectSum()

public selectSum([string $select = = '\'\'' ][, string $alias = = '\'\'' ]) : $this
Parameters
$select : string = = '\'\''
$alias : string = = '\'\''
Return values
$this

set()

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.

public set(object|row_array|string $key[, bool|float|int|object|string|null $value = '' ][, bool|null $escape = null ]) : $this
Parameters
$key : object|row_array|string

Field name, or an array of field/value pairs, or an object

$value : bool|float|int|object|string|null = ''

Field value, if $key is a single field

$escape : bool|null = null

Whether to escape values

Return values
$this

setAllowedFields()

It could be used when you have to change default or override current allowed fields.

public setAllowedFields(array<int, string> $allowedFields) : $this
Parameters
$allowedFields : array<int, string>

Array with names of fields.

Return values
$this

setTable()

Specify the table associated with a model.

public setTable(string $table) : $this
Parameters
$table : string
Return values
$this

setValidationMessage()

Allows to set field wise validation message.

public setValidationMessage(string $field, array<string, string> $fieldMessages) : $this

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

Parameters
$field : string
$fieldMessages : array<string, string>
Return values
$this

setValidationMessages()

Allows to set (and reset) validation messages.

public setValidationMessages(array<string, array<string, string>> $validationMessages) : $this

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

Parameters
$validationMessages : array<string, array<string, string>>
Return values
$this

setValidationRule()

Allows to set field wise validation rules.

public setValidationRule(string $field, array<string, array<string, string>|string>|string $fieldRules) : $this

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

Parameters
$field : string
$fieldRules : array<string, array<string, string>|string>|string
Return values
$this

setValidationRules()

Allows to set (and reset) validation rules.

public setValidationRules(array<string, array<string, array<string, string>|string>|string> $validationRules) : $this

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

Parameters
$validationRules : array<string, array<string, array<string, string>|string>|string>
Return values
$this

skipValidation()

Set the value of the $skipValidation flag.

public skipValidation([bool $skip = true ]) : $this
Parameters
$skip : bool = true
Return values
$this

update()

Updates a single record in the database. If an object is provided, it will attempt to convert it into an array.

public update([mixed $id = null ][, mixed $row = null ]) : bool
Parameters
$id : mixed = null
$row : mixed = null
Return values
bool

updateBatch()

Compiles an update and runs the query.

public updateBatch([array<int, object|row_array>|null $set = null ][, string|null $index = null ][, int $batchSize = 100 ][, bool $returnSQL = false ]) : false|int|array<int, string>
Parameters
$set : array<int, object|row_array>|null = null

An associative array of insert values.

$index : string|null = null

The where key.

$batchSize : int = 100

The size of the batch to run.

$returnSQL : bool = false

true means SQL is returned, false will execute the query.

Tags
throws
DatabaseException
throws
ReflectionException
Return values
false|int|array<int, string>

Number of rows affected or false on failure, SQL array when test mode.

validate()

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

public validate(object|row_array $row) : bool
Parameters
$row : object|row_array
Return values
bool

when()

public when(mixed $condition, callable $callback[, callable|null $defaultCallback = = 'null' ]) : $this
Parameters
$condition : mixed
$callback : callable
$defaultCallback : callable|null = = 'null'
Return values
$this

whenNot()

public whenNot(mixed $condition, callable $callback[, callable|null $defaultCallback = = 'null' ]) : $this
Parameters
$condition : mixed
$callback : callable
$defaultCallback : callable|null = = 'null'
Return values
$this

where()

public where(mixed $key[, mixed $value = = 'null' ][, bool|null $escape = = 'null' ]) : $this
Parameters
$key : mixed
$value : mixed = = 'null'
$escape : bool|null = = 'null'
Return values
$this

whereIn()

public whereIn([string|null $key = = 'null' ][, mixed $values = = 'null' ][, bool|null $escape = = 'null' ]) : $this
Parameters
$key : string|null = = 'null'
$values : mixed = = 'null'
$escape : bool|null = = 'null'
Return values
$this

whereNotIn()

public whereNotIn([string|null $key = = 'null' ][, mixed $values = = 'null' ][, bool|null $escape = = 'null' ]) : $this
Parameters
$key : string|null = = 'null'
$values : mixed = = 'null'
$escape : bool|null = = 'null'
Return values
$this

withDeleted()

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

public withDeleted([bool $val = true ]) : $this
Parameters
$val : bool = true
Return values
$this

cleanValidationRules()

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.

protected cleanValidationRules(array<string, array<string, array<string, string>|string>|string> $rules, row_array $row) : array<string, array<string, array<string, string>|string>|string>
Parameters
$rules : array<string, array<string, array<string, string>|string>|string>
$row : row_array
Return values
array<string, array<string, array<string, string>|string>|string>

convertToReturnType()

Converts database data array to return type value.

protected convertToReturnType(array<string, mixed> $row, "array"|"object"|class-string $returnType) : array<string, mixed>|object
Parameters
$row : array<string, mixed>

Raw data from database.

$returnType : "array"|"object"|class-string
Return values
array<string, mixed>|object

createDataConverter()

Creates DataConverter instance.

protected createDataConverter() : void

doDelete()

Deletes a single record from the database where $id matches the table's primary key.

protected doDelete([mixed $id = null ][, bool $purge = false ]) : bool|string

This method works only with DB calls.

Parameters
$id : mixed = null

The rows primary key(s).

$purge : bool = false

Allows overriding the soft deletes setting.

Return values
bool|string

Returns a SQL string if in test mode.

doErrors()

Grabs the last error(s) that occurred from the Database connection.

protected doErrors() : array<string, string>

The return array should be in the following format: ['source' => 'message']. This method works only with dbCalls.

Return values
array<string, string>

doFind()

Fetches the row(s) of database with a primary key matching $id.

protected doFind(bool $singleton[, mixed $id = null ]) : row_array>)

This method works only with DB calls.

Parameters
$singleton : bool

Single or multiple results.

$id : mixed = null

One primary key or an array of primary keys.

Return values
row_array>)

The resulting row of data or null.

doFindAll()

Fetches all results, while optionally limiting them.

protected doFindAll([int|null $limit = null ][, int $offset = 0 ]) : array<int, object|row_array>

Works with the current Query Builder instance.

Parameters
$limit : int|null = null
$offset : int = 0
Return values
array<int, object|row_array>

doFindColumn()

Fetches the column of database.

protected doFindColumn(string $columnName) : array<int, row_array>|null

This method works only with DB calls.

Parameters
$columnName : string
Return values
array<int, row_array>|null

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

doFirst()

Returns the first row of the result set.

protected doFirst() : object|row_array|null

Will take any previous Query Builder calls into account when determining the result set.

Return values
object|row_array|null

doInsert()

Inserts data into the current database.

protected doInsert(array<string|int, mixed> $row) : bool

This method works only with DB calls.

Parameters
$row : array<string|int, mixed>
Return values
bool

doInsertBatch()

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

protected doInsertBatch([array<string|int, mixed>|null $set = null ][, bool|null $escape = null ][, int $batchSize = 100 ][, bool $testing = false ]) : false|int|array<int, string>

This method works only with DB calls.

Parameters
$set : array<string|int, mixed>|null = null

An associative array of insert values.

$escape : bool|null = null

Whether to escape values.

$batchSize : int = 100

The size of the batch to run.

$testing : bool = false

true means only number of records is returned, false will execute the query.

Return values
false|int|array<int, string>

Number of rows affected or false on failure, SQL array when test mode

doOnlyDeleted()

Works with the $this->find* methods to return only the rows that have been deleted (value of column $deletedField is not null).

protected doOnlyDeleted() : void

This method works only with DB calls.

doProtectFields()

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

protected doProtectFields(row_array $row) : row_array
Parameters
$row : row_array
Tags
used-by

update() to protect against mass assignment vulnerabilities.

used-by

updateBatch() to protect against mass assignment vulnerabilities.

throws
DataException
Return values
row_array

doProtectFieldsForInsert()

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

protected doProtectFieldsForInsert(array<string|int, mixed> $row) : row_array
Parameters
$row : array<string|int, mixed>
Return values
row_array

doPurgeDeleted()

Permanently deletes all rows that have been marked as deleted through soft deletes (value of column $deletedField is not null).

protected doPurgeDeleted() : bool|string

This method works only with DB calls.

Return values
bool|string

Returns a SQL string if in test mode.

doReplace()

Compiles a replace and runs the query.

protected doReplace([array<string|int, mixed>|null $row = null ][, bool $returnSQL = false ]) : BaseResult|false|Query|string

This method works only with DB calls.

Parameters
$row : array<string|int, mixed>|null = null
$returnSQL : bool = false

true means SQL is returned, false will execute the query.

Return values
BaseResult|false|Query|string

doUpdate()

Updates a single record in the database.

protected doUpdate([mixed $id = null ][, mixed $row = null ]) : bool

This method works only with DB calls.

Parameters
$id : mixed = null
$row : mixed = null
Return values
bool

doUpdateBatch()

Compiles an update and runs the query.

protected doUpdateBatch([array<string|int, mixed>|null $set = null ][, string|null $index = null ][, int $batchSize = 100 ][, bool $returnSQL = false ]) : false|int|array<int, string>

This method works only with DB calls.

Parameters
$set : array<string|int, mixed>|null = null

An associative array of update values.

$index : string|null = null

The where key.

$batchSize : int = 100

The size of the batch to run.

$returnSQL : bool = false

true means SQL is returned, false will execute the query.

Return values
false|int|array<int, string>

Number of rows affected or false on failure, SQL array when test mode

ensureValidation()

protected ensureValidation() : void

initialize()

Initializes the instance with any additional steps.

protected initialize() : void

Optionally implemented by child classes.

intToDate()

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.

protected intToDate(int $value) : int|string

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
$value : int
Tags
throws
ModelException
Return values
int|string

objectToArray()

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

protected objectToArray(object $object[, bool $onlyChanged = true ][, bool $recursive = false ]) : array<string, mixed>

This method uses $this->objectToRawArray() internally and does conversion to string on all Time instances.

Parameters
$object : object
$onlyChanged : bool = true

Returns only the changed properties.

$recursive : bool = false

If true, inner entities will be cast as array as well.

Tags
throws
ReflectionException
Return values
array<string, mixed>

objectToRawArray()

Takes a class and returns an array of its public and protected properties as an array with raw values.

protected objectToRawArray(mixed $object[, bool $onlyChanged = true ][, bool $recursive = false ]) : array<string, mixed>
Parameters
$object : mixed
$onlyChanged : bool = true

Returns only the changed properties.

$recursive : bool = false

If true, inner entities will be cast as array as well.

Return values
array<string, mixed>

Array with raw values

setCreatedField()

Set datetime to created field.

protected setCreatedField(row_array $row, int|string $date) : row_array
Parameters
$row : row_array
$date : int|string

Timestamp or datetime string.

Return values
row_array

setDate()

Sets the timestamp or current timestamp if null value is passed.

protected setDate([int|null $userDate = null ]) : int|string
Parameters
$userDate : int|null = null

An optional PHP timestamp to be converted

Tags
throws
ModelException
Return values
int|string

setUpdatedField()

Set datetime to updated field.

protected setUpdatedField(row_array $row, int|string $date) : row_array
Parameters
$row : row_array
$date : int|string

Timestamp or datetime string

Return values
row_array

shouldUpdate()

This method is called on save to determine if entry have to be updated.

protected shouldUpdate(mixed $row) : bool

If this method returns false insert operation will be executed.

Parameters
$row : mixed
Return values
bool

timeToDate()

Converts Time value to string using $this->dateFormat.

protected timeToDate(Time $value) : int|string

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
$value : Time
Return values
int|string

timeToString()

Convert any Time instances to appropriate $dateFormat.

protected timeToString(array<string, mixed> $properties) : array<string, mixed>
Parameters
$properties : array<string, mixed>
Return values
array<string, mixed>

transformDataToArray()

Transform data to array.

protected transformDataToArray(object|row_array|null $row, string $type) : array<int|string, mixed>
Parameters
$row : object|row_array|null
$type : string
Tags
throws
DataException
throws
InvalidArgumentException
throws
ReflectionException
used-by

insert()

used-by

insertBatch()

used-by

update()

used-by

updateBatch()

Return values
array<int|string, mixed>

trigger()

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.

protected trigger(string $event, TEventData $eventData) : TEventData

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

Each $eventData 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.)

If callbacks are not allowed then returns $eventData immediately.

Parameters
$event : string

Valid property of the model event: $this->before*, $this->after*, etc.

$eventData : TEventData
Tags
template
throws
DataException
Return values
TEventData

useCasts()

Are casts used?

protected useCasts() : bool
Return values
bool

validateID()

Validates that the primary key values are valid for update/delete/insert operations.

protected validateID(mixed $id[, bool $allowArray = true ]) : void

Throws exception if invalid.

Parameters
$id : mixed
$allowArray : bool = true

Whether to allow array of IDs (true for update/delete, false for insert)

Tags
phpstan-assert

non-zero-int|non-empty-list<int|string>|RawSql|non-falsy-string $id

throws
InvalidArgumentException

checkBuilderMethod()

Checks the Builder method name that should not be used in the Model.

private checkBuilderMethod(string $name) : void
Parameters
$name : string

        
On this page

Search results