CodeIgniter v4.5 API

BaseModel
in package

AbstractYes

The BaseModel class provides a number of convenient features that makes working with a databases less painful. Extending this class provide means of implementing various database systems

It will:

  • simplifies pagination
  • allow specifying the return type (array, object, etc) with each call
  • automatically set and update timestamps
  • handle soft deletes
  • ensure validation is run against objects when saving items
  • process various callbacks
  • allow intermingling calls to the db connection
Tags
phpstan-type

row_array array<int|string, float|int|null|object|string>

phpstan-type

event_data_beforeinsert array{data: row_array}

phpstan-type

event_data_afterinsert array{id: int|string, data: row_array, result: bool}

phpstan-type

event_data_beforefind array{id?: int|string, method: string, singleton: bool, limit?: int, offset?: int}

phpstan-type

event_data_afterfind array{id: int|string|null|list<int|string>, data: row_array|list<row_array>|object|null, method: string, singleton: bool}

phpstan-type

event_data_beforeupdate array{id: null|list<int|string>, data: row_array}

phpstan-type

event_data_afterupdate array{id: null|list<int|string>, data: row_array|object, result: bool}

phpstan-type

event_data_beforedelete array{id: null|list<int|string>, purge: bool}

phpstan-type

event_data_afterdelete array{id: null|list<int|string>, data: null, purge: bool, result: bool}

Table of Contents

Properties

$pager  : Pager
Pager instance.
$afterDelete  : array<int, string>
Callbacks for afterDelete
$afterFind  : array<int, string>
Callbacks for afterFind
$afterInsert  : array<int, string>
Callbacks for afterInsert
$afterInsertBatch  : array<int, string>
Callbacks for afterInsertBatch
$afterUpdate  : array<int, string>
Callbacks for afterUpdate
$afterUpdateBatch  : array<int, string>
Callbacks for afterUpdateBatch
$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
$beforeFind  : array<int, string>
Callbacks for beforeFind
$beforeInsert  : array<int, string>
Callbacks for beforeInsert
$beforeInsertBatch  : array<int, string>
Callbacks for beforeInsertBatch
$beforeUpdate  : array<int, string>
Callbacks for beforeUpdate
$beforeUpdateBatch  : array<int, string>
Callbacks for beforeUpdateBatch
$castHandlers  : array<string, class-string>
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  : string
The type of column that created_at and updated_at are expected to.
$db  : BaseConnection
Database Connection
$DBGroup  : non-empty-string|null
The Database connection group that should be instantiated.
$deletedField  : string
The column used to save soft delete state
$insertID  : int|string
Last insert ID
$protectFields  : bool
If this model should use "softDeletes" and simply set a date when rows are deleted, or do hard deletes.
$returnType  : string
The format that the results should be returned as.
$skipValidation  : bool
Skip the model's validation. Used in conjunction with skipValidation() to skip data validation for any future calls.
$tempAllowCallbacks  : bool
Used by allowCallbacks() to override the model's allowCallbacks setting.
$tempReturnType  : "array"|"object"|class-string
Used by asArray() and asObject() to provide temporary overrides of model default.
$tempUseSoftDeletes  : bool
Used by 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.
$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(), and save() methods.

Methods

__call()  : $this|null
Provides direct access to method in the database connection.
__construct()  : mixed
__get()  : array<string|int, mixed>|bool|float|int|object|string|null
Provides the db connection and model's properties.
__isset()  : bool
Checks for the existence of properties across this model, 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.
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()  : BaseResult|bool
Deletes a single record from the database where $id matches.
errors()  : array<string, string>
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.
find()  : array<string|int, mixed>|object|null
Fetches the row of database.
findAll()  : array<string|int, mixed>
Fetches all results, while optionally limiting them.
findColumn()  : array<string|int, mixed>|null
Fetches the column of database.
first()  : array<string|int, mixed>|object|null
Returns the first row of the result set.
getIdValue()  : array<string|int, mixed>|int|string|null
Public getter to return the id value using the idValue() method.
getInsertID()  : int|string
Returns last insert ID or 0.
getValidationMessages()  : array<string|int, mixed>
Returns the model's validation messages, so they can be used elsewhere, if needed.
getValidationRules()  : array<string|int, mixed>
Returns the model's defined validation rules so that they can be used elsewhere, if needed.
insert()  : bool|int|string
Inserts data into the database. If an object is provided, it will attempt to convert it to an array.
insertBatch()  : bool|int
Compiles batch insert runs the queries, validating each row prior.
onlyDeleted()  : $this
Works with the find* methods to return only the rows that have been deleted.
paginate()  : array<string|int, mixed>|null
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 (deleted = 1).
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. 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.
setAllowedFields()  : $this
It could be used when you have to change default or override current allowed fields.
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.
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|int, mixed>
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|int, 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.
doErrors()  : array<string, string>
Grabs the last error(s) that occurred from the Database connection.
doFind()  : array<string|int, mixed>|object|null
Fetches the row of database.
doFindAll()  : array<string|int, mixed>
Fetches all results, while optionally limiting them.
doFindColumn()  : array<string|int, mixed>|null
Fetches the column of database.
doFirst()  : array<string|int, mixed>|object|null
Returns the first row of the result set.
doInsert()  : bool
Inserts data into the current database.
doInsertBatch()  : bool|int
Compiles batch insert and runs the queries, validating each row prior.
doOnlyDeleted()  : void
Works with the find* methods to return only the rows that have been deleted.
doProtectFields()  : array<string|int, mixed>
Ensures that only the fields that are allowed to be updated are in the data array.
doProtectFieldsForInsert()  : array<string|int, mixed>
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.
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()  : array<string|int, mixed>
Set datetime to created field.
setDate()  : int|string
Sets the date or current date if null value is passed.
setUpdatedField()  : array<string|int, mixed>
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<string|int, mixed>
Transform data to array.
trigger()  : array<string|int, 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.
useCasts()  : bool
Are casts used?

Properties

$pager

Pager instance.

public Pager $pager

Populated after calling $this->paginate()

$afterDelete

Callbacks for afterDelete

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

$afterFind

Callbacks for afterFind

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

$afterInsert

Callbacks for afterInsert

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

$afterInsertBatch

Callbacks for afterInsertBatch

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

$afterUpdate

Callbacks for afterUpdate

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

$afterUpdateBatch

Callbacks for afterUpdateBatch

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

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

$beforeFind

Callbacks for beforeFind

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

$beforeInsert

Callbacks for beforeInsert

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

$beforeInsertBatch

Callbacks for beforeInsertBatch

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

$beforeUpdate

Callbacks for beforeUpdate

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

$beforeUpdateBatch

Callbacks for beforeUpdateBatch

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

$castHandlers

Custom convert handlers.

protected array<string, class-string> $castHandlers = []

[type => classname]

$casts

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

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

[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 string $dateFormat = 'datetime'

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

$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'

$insertID

Last insert ID

protected int|string $insertID = 0

$protectFields

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

protected bool $protectFields = true

$returnType

The format that the results should be returned as.

protected string $returnType = 'array'

Will be overridden if the as* methods are used.

$skipValidation

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

protected bool $skipValidation = false

$tempAllowCallbacks

Used by allowCallbacks() to override the model's allowCallbacks setting.

protected bool $tempAllowCallbacks

$tempReturnType

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

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

$tempUseSoftDeletes

Used by 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

$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 = []

Methods

__call()

Provides direct access to method in the database connection.

public __call(string $name, array<string|int, mixed> $params) : $this|null
Parameters
$name : string

Name

$params : array<string|int, mixed>

Params

Return values
$this|null

__get()

Provides the db connection and model's properties.

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

Name

Return values
array<string|int, mixed>|bool|float|int|object|string|null

__isset()

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

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

Name

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

value

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'

Class Name

Return values
$this

chunk()

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

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

This method works only with dbCalls.

Parameters
$size : int

Size

$userFunc : Closure

Callback Function

Tags
throws
DataException

cleanRules()

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

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

Value

Return values
$this

countAllResults()

Override countAllResults to account for soft deleted accounts.

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

This method works only with dbCalls.

Parameters
$reset : bool = true

Reset

$test : bool = false

Test

Return values
int|string

delete()

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

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

The rows primary key(s)

$purge : bool = false

Allows overriding the soft deletes setting.

Tags
throws
DatabaseException
Return values
BaseResult|bool

errors()

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.

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

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([array<string|int, mixed>|int|string|null $id = null ]) : array<string|int, mixed>|object|null
Parameters
$id : array<string|int, mixed>|int|string|null = null

One primary key or an array of primary keys

Tags
phpstan-return

($id is int|string ? row_array|object|null : list<row_array|object>)

Return values
array<string|int, mixed>|object|null

The resulting row of data, or null.

findAll()

Fetches all results, while optionally limiting them.

public findAll([int $limit = null ][, int $offset = 0 ]) : array<string|int, mixed>
Parameters
$limit : int = null

Limit

$offset : int = 0

Offset

Return values
array<string|int, mixed>

findColumn()

Fetches the column of database.

public findColumn(string $columnName) : array<string|int, mixed>|null
Parameters
$columnName : string

Column Name

Tags
throws
DataException
Return values
array<string|int, mixed>|null

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

first()

Returns the first row of the result set.

public first() : array<string|int, mixed>|object|null
Return values
array<string|int, mixed>|object|null

getIdValue()

Public getter to return the id value using the idValue() method.

public abstract getIdValue(array<string|int, mixed>|object $row) : array<string|int, mixed>|int|string|null

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

Parameters
$row : array<string|int, mixed>|object

Row data

Tags
phpstan-param

row_array|object $row

Return values
array<string|int, mixed>|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|int, mixed>
Return values
array<string|int, mixed>

getValidationRules()

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

public getValidationRules([array<string|int, mixed> $options = [] ]) : array<string|int, mixed>
Parameters
$options : array<string|int, mixed> = []

Options

Return values
array<string|int, mixed>

insert()

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

public insert([array<string|int, mixed>|object|null $row = null ][, bool $returnID = true ]) : bool|int|string
Parameters
$row : array<string|int, mixed>|object|null = null

Row data

$returnID : bool = true

Whether insert ID should be returned or not.

Tags
phpstan-param

row_array|object|null $row

phpstan-return

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

throws
ReflectionException
Return values
bool|int|string

insert ID or true on success. false on failure.

insertBatch()

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

public insertBatch([array<int, array<string|int, mixed>|object>|null $set = null ][, bool|null $escape = null ][, int $batchSize = 100 ][, bool $testing = false ]) : bool|int
Parameters
$set : array<int, array<string|int, mixed>|object>|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
phpstan-param

list<row_array|object>|null $set

throws
ReflectionException
Return values
bool|int

Number of rows inserted or FALSE on failure

onlyDeleted()

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

public onlyDeleted() : $this
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<string|int, mixed>|null

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<string|int, mixed>|null

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

Value

Return values
$this

purgeDeleted()

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

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

Returns a string if in test mode.

replace()

Compiles a replace and runs the query.

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

Row data

$returnSQL : bool = false

Set to true to return Query String

Tags
phpstan-param

row_array|null $row

Return values
BaseResult|false|Query|string

save()

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.

public save(array<string|int, mixed>|object $row) : bool
Parameters
$row : array<string|int, mixed>|object

Row data

Tags
phpstan-param

row_array|object $row

throws
ReflectionException
Return values
bool

setAllowedFields()

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

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

Array with names of fields

Return values
$this

setValidationMessage()

Allows to set field wise validation message.

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

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

Parameters
$field : string

Field Name

$fieldMessages : array<string|int, mixed>

Validation messages

Return values
$this

setValidationMessages()

Allows to set (and reset) validation messages.

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

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

Parameters
$validationMessages : array<string|int, mixed>

Value

Return values
$this

setValidationRule()

Allows to set field wise validation rules.

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

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

Parameters
$field : string

Field Name

$fieldRules : array<string|int, mixed>|string

Validation rules

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>

Value

Return values
$this

skipValidation()

Set the value of the skipValidation flag.

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

Value

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([array<string|int, mixed>|int|string|null $id = null ][, array<string|int, mixed>|object|null $row = null ]) : bool
Parameters
$id : array<string|int, mixed>|int|string|null = null
$row : array<string|int, mixed>|object|null = null

Row data

Tags
phpstan-param

row_array|object|null $row

throws
ReflectionException
Return values
bool

updateBatch()

Compiles an update and runs the query.

public updateBatch([array<int, array<string|int, mixed>|object>|null $set = null ][, string|null $index = null ][, int $batchSize = 100 ][, bool $returnSQL = false ]) : false|int|array<int, string>
Parameters
$set : array<int, array<string|int, mixed>|object>|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
phpstan-param

list<row_array|object>|null $set

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

Number of rows affected or FALSE on failure, SQL array when testMode

validate()

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

public validate(array<string|int, mixed>|object $row) : bool
Parameters
$row : array<string|int, mixed>|object

Row data

Tags
phpstan-param

row_array|object $row

Return values
bool

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

Value

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|int, mixed> $rules[, array<string|int, mixed> $row = null ]) : array<string|int, mixed>
Parameters
$rules : array<string|int, mixed>

Array containing field name and rule

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

Row data (@TODO Remove null in param type)

Tags
phpstan-param

row_array $row

Return values
array<string|int, mixed>

convertToReturnType()

Converts database data array to return type value.

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

Raw data from database

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

createDataConverter()

Creates DataConverter instance.

protected createDataConverter() : void

doDelete()

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

protected abstract doDelete([array<string|int, mixed>|int|string|null $id = null ][, bool $purge = false ]) : bool|string

This method works only with dbCalls.

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

The rows primary key(s)

$purge : bool = false

Allows overriding the soft deletes setting.

Tags
throws
DatabaseException
Return values
bool|string

doErrors()

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

protected abstract doErrors() : array<string, string>

This method works only with dbCalls.

Return values
array<string, string>

doFind()

Fetches the row of database.

protected abstract doFind(bool $singleton[, array<string|int, mixed>|int|string|null $id = null ]) : array<string|int, mixed>|object|null

This method works only with dbCalls.

Parameters
$singleton : bool

Single or multiple results

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

One primary key or an array of primary keys

Return values
array<string|int, mixed>|object|null

The resulting row of data, or null.

doFindAll()

Fetches all results, while optionally limiting them.

protected abstract doFindAll([int|null $limit = null ][, int $offset = 0 ]) : array<string|int, mixed>

This method works only with dbCalls.

Parameters
$limit : int|null = null

Limit

$offset : int = 0

Offset

Return values
array<string|int, mixed>

doFindColumn()

Fetches the column of database.

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

This method works only with dbCalls.

Parameters
$columnName : string

Column Name

Tags
throws
DataException
Return values
array<string|int, mixed>|null

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

doFirst()

Returns the first row of the result set.

protected abstract doFirst() : array<string|int, mixed>|object|null

This method works only with dbCalls.

Return values
array<string|int, mixed>|object|null

doInsert()

Inserts data into the current database.

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

This method works only with dbCalls.

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

Row data

Tags
phpstan-param

row_array $row

Return values
bool

doInsertBatch()

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

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

This method works only with dbCalls.

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
bool|int

Number of rows inserted or FALSE on failure

doOnlyDeleted()

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

protected abstract doOnlyDeleted() : void

This method works only with dbCalls.

doProtectFields()

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

protected doProtectFields(array<string|int, mixed> $row) : array<string|int, mixed>
Parameters
$row : array<string|int, mixed>

Row data

Tags
used-by

update() to protect against mass assignment vulnerabilities.

used-by

updateBatch() to protect against mass assignment vulnerabilities.

phpstan-param

row_array $row

throws
DataException
Return values
array<string|int, mixed>

doProtectFieldsForInsert()

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

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

Row data

Tags
used-by

insert() to protect against mass assignment vulnerabilities.

used-by

insertBatch() to protect against mass assignment vulnerabilities.

phpstan-param

row_array $row

throws
DataException
Return values
array<string|int, mixed>

doPurgeDeleted()

Permanently deletes all rows that have been marked as deleted.

protected abstract doPurgeDeleted() : bool|string

through soft deletes (deleted = 1). This method works only with dbCalls.

Return values
bool|string

Returns a string if in test mode.

doReplace()

Compiles a replace and runs the query.

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

This method works only with dbCalls.

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

Row data

$returnSQL : bool = false

Set to true to return Query String

Tags
phpstan-param

row_array|null $row

Return values
BaseResult|false|Query|string

doUpdate()

Updates a single record in the database.

protected abstract doUpdate([array<string|int, mixed>|int|string|null $id = null ][, array<string|int, mixed>|null $row = null ]) : bool

This method works only with dbCalls.

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

ID

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

Row data

Tags
phpstan-param

row_array|null $row

Return values
bool

doUpdateBatch()

Compiles an update and runs the query.

protected abstract 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 dbCalls.

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

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

Number of rows affected or FALSE on failure, SQL array when testMode

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

value

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 objectToRawArray() internally and does conversion to string on all Time instances

Parameters
$object : object

Object

$onlyChanged : bool = true

Only Changed Property

$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(object $object[, bool $onlyChanged = true ][, bool $recursive = false ]) : array<string, mixed>
Parameters
$object : object

Object

$onlyChanged : bool = true

Only Changed Property

$recursive : bool = false

If true, inner entities will be casted as array as well

Tags
throws
ReflectionException
Return values
array<string, mixed>

Array with raw values.

setCreatedField()

Set datetime to created field.

protected setCreatedField(array<string|int, mixed> $row, int|string $date) : array<string|int, mixed>
Parameters
$row : array<string|int, mixed>
$date : int|string

timestamp or datetime string

Tags
phpstan-param

row_array $row

Return values
array<string|int, mixed>

setDate()

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

protected setDate([int|null $userData = null ]) : int|string
Parameters
$userData : 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(array<string|int, mixed> $row, int|string $date) : array<string|int, mixed>
Parameters
$row : array<string|int, mixed>
$date : int|string

timestamp or datetime string

Tags
phpstan-param

row_array $row

Return values
array<string|int, mixed>

shouldUpdate()

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

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

If this method returns false insert operation will be executed

Parameters
$row : array<string|int, mixed>|object

Row data

Tags
phpstan-param

row_array|object $row

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

value

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(array<string|int, mixed>|object|null $row, string $type) : array<string|int, mixed>
Parameters
$row : array<string|int, mixed>|object|null

Row data

$type : string

Type of data (insert|update)

Tags
phpstan-param

row_array|object|null $row

throws
DataException
throws
InvalidArgumentException
throws
ReflectionException
used-by

insert()

used-by

update()

Return values
array<string|int, 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, array<string|int, mixed> $eventData) : array<string|int, mixed>

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

Event

$eventData : array<string|int, mixed>

Event Data

Tags
throws
DataException
Return values
array<string|int, mixed>

useCasts()

Are casts used?

protected useCasts() : bool
Return values
bool

        
On this page

Search results