PHP Class Cake\ORM\Table

Exposes methods for retrieving data out of it, and manages the associations this table has to other tables. Multiple instances of this class can be created for the same database table with different aliases, this allows you to address your database structure in a richer and more expressive way. ### Retrieving data The primary way to retrieve data is using Table::find(). See that method for more information. ### Dynamic finders In addition to the standard find($type) finder methods, CakePHP provides dynamic finder methods. These methods allow you to easily set basic conditions up. For example to filter users by username you would call $query = $users->findByUsername('mark'); You can also combine conditions on multiple fields using either Or or And: $query = $users->findByUsernameOrEmail('mark', '[email protected]'); ### Bulk updates/deletes You can use Table::updateAll() and Table::deleteAll() to do bulk updates/deletes. You should be aware that events will *not* be fired for bulk updates/deletes. ### Callbacks/events Table objects provide a few callbacks/events you can hook into to augment/replace find operations. Each event uses the standard event subsystem in CakePHP - beforeFind(Event $event, Query $query, ArrayObject $options, boolean $primary) Fired before each find operation. By stopping the event and supplying a return value you can bypass the find operation entirely. Any changes done to the $query instance will be retained for the rest of the find. The $primary parameter indicates whether or not this is the root query, or an associated query. - buildValidator(Event $event, Validator $validator, string $name) Allows listeners to modify validation rules for the provided named validator. - buildRules(Event $event, RulesChecker $rules) Allows listeners to modify the rules checker by adding more rules. - beforeRules(Event $event, EntityInterface $entity, ArrayObject $options, string $operation) Fired before an entity is validated using the rules checker. By stopping this event, you can return the final value of the rules checking operation. - afterRules(Event $event, EntityInterface $entity, ArrayObject $options, bool $result, string $operation) Fired after the rules have been checked on the entity. By stopping this event, you can return the final value of the rules checking operation. - beforeSave(Event $event, EntityInterface $entity, ArrayObject $options) Fired before each entity is saved. Stopping this event will abort the save operation. When the event is stopped the result of the event will be returned. - afterSave(Event $event, EntityInterface $entity, ArrayObject $options) Fired after an entity is saved. - afterSaveCommit(Event $event, EntityInterface $entity, ArrayObject $options) Fired after the transaction in which the save operation is wrapped has been committed. It’s also triggered for non atomic saves where database operations are implicitly committed. The event is triggered only for the primary table on which save() is directly called. The event is not triggered if a transaction is started before calling save. - beforeDelete(Event $event, EntityInterface $entity, ArrayObject $options) Fired before an entity is deleted. By stopping this event you will abort the delete operation. - afterDelete(Event $event, EntityInterface $entity, ArrayObject $options) Fired after an entity has been deleted.
See also: Cake\Event\EventManager for reference on the events system.
Inheritance: implements Cake\Datasource\RepositoryInterface, implements Cake\Event\EventListenerInterface, implements Cake\Event\EventDispatcherInterface, use trait Cake\Event\EventDispatcherTrait, use trait Cake\Datasource\RulesAwareTrait, use trait Cake\Validation\ValidatorAwareTrait
Show file Open project: cakephp/orm Class Usage Examples

Protected Properties

Property Type Description
$_alias string Human name giving to this particular instance. Multiple objects representing the same database table can exist by using different aliases.
$_associations Cake\ORM\AssociationCollection The associations container for this Table.
$_behaviors Cake\ORM\BehaviorRegistry BehaviorRegistry for this table
$_connection Cake\Datasource\ConnectionInterface Connection instance
$_displayField string The name of the field that represents a human readable representation of a row
$_entityClass string The name of the class that represent a single row for this table
$_primaryKey string | array The name of the field that represents the primary key in the table
$_registryAlias string Registry key used to create this table object
$_schema Cake\Database\Schema\Table The schema object containing a description of this table fields
$_table string Name of the table as it can be found in the database

Public Methods

Method Description
__call ( string $method, array $args ) : mixed Handles behavior delegation + dynamic finders.
__construct ( array $config = [] ) Initializes a new instance
__debugInfo ( ) : array Returns an array that can be used to describe the internal state of this object.
__get ( string $property ) : Cake\ORM\Association Returns the association named after the passed value if exists, otherwise throws an exception.
__isset ( string $property ) : boolean Returns whether an association named after the passed value exists for this table.
addAssociations ( array $params ) : void Setup multiple associations.
addBehavior ( string $name, array $options = [] ) : void Add a behavior.
alias ( $alias = null ) {@inheritDoc}
aliasField ( string $field ) : string Alias a field with the table's current alias.
association ( string $name ) : Cake\ORM\Association | null Returns an association object configured for the specified alias if any
associations ( ) : Cake\ORM\AssociationCollection Get the associations collection for this table.
behaviors ( ) : Cake\ORM\BehaviorRegistry Returns the behavior registry for this table.
belongsTo ( string $associated, array $options = [] ) : Cake\ORM\Association\BelongsTo Creates a new BelongsTo association between this table and a target table. A "belongs to" association is a N-1 relationship where this table is the N side, and where there is a single associated record in the target table for each one in this table.
belongsToMany ( string $associated, array $options = [] ) : BelongsToMany Creates a new BelongsToMany association between this table and a target table. A "belongs to many" association is a M-N relationship.
buildRules ( Cake\ORM\RulesChecker $rules ) : Cake\ORM\RulesChecker {@inheritDoc}
callFinder ( string $type, Query $query, array $options = [] ) : Query Calls a finder method directly and applies it to the passed query, if no query is passed a new one will be created and returned
connection ( Cake\Datasource\ConnectionInterface $conn = null ) : Cake\Datasource\ConnectionInterface Returns the connection instance or sets a new one
defaultConnectionName ( ) : string Get the default connection name.
delete ( Cake\Datasource\EntityInterface $entity, $options = [] ) {@inheritDoc}
deleteAll ( $conditions ) {@inheritDoc}
displayField ( string | null $key = null ) : string Returns the display field or sets a new one
entityClass ( string | null $name = null ) : string Returns the class used to hydrate rows for this table or sets a new one
exists ( $conditions ) {@inheritDoc}
find ( $type = 'all', $options = [] ) : Query {@inheritDoc}
findAll ( Query $query, array $options ) : Query Returns the query as passed.
findList ( Query $query, array $options ) : Query Sets up a query object so results appear as an indexed array, useful for any place where you would want a list such as for populating input select boxes.
findOrCreate ( array | Query $search, callable $callback = null, array $options = [] ) : Cake\Datasource\EntityInterface Finds an existing record or creates a new one.
findThreaded ( Query $query, array $options ) : Query Results for this finder will be a nested array, and is appropriate if you want to use the parent_id field of your model data to build nested results.
get ( $primaryKey, $options = [] ) {@inheritDoc}
getSaveOptionsBuilder ( array $options = [] ) : Cake\ORM\SaveOptionsBuilder Gets a SaveOptionsBuilder instance.
hasBehavior ( string $name ) : boolean Check if a behavior with the given alias has been loaded.
hasField ( string $field ) : boolean Test to see if a Table has a specific field/column.
hasFinder ( string $type ) : boolean Returns true if the finder exists for the table
hasMany ( string $associated, array $options = [] ) : Cake\ORM\Association\HasMany Creates a new HasMany association between this table and a target table. A "has many" association is a 1-N relationship.
hasOne ( string $associated, array $options = [] ) : Cake\ORM\Association\HasOne Creates a new HasOne association between this table and a target table. A "has one" association is a 1-1 relationship.
implementedEvents ( ) : array Get the Model callbacks this table is interested in.
initialize ( array $config ) : void Initialize a table instance. Called after the constructor.
loadInto ( Cake\Datasource\EntityInterface | array $entities, array $contain ) : Cake\Datasource\EntityInterface | array Loads the specified associations in the passed entity or list of entities by executing extra queries in the database and merging the results in the appropriate properties.
marshaller ( ) : Cake\ORM\Marshaller Get the object used to marshal/convert array data into objects.
newEntities ( array $data, array $options = [] ) {@inheritDoc}
newEntity ( $data = null, array $options = [] ) {@inheritDoc}
patchEntities ( $entities, array $data, array $options = [] ) {@inheritDoc}
patchEntity ( Cake\Datasource\EntityInterface $entity, array $data, array $options = [] ) {@inheritDoc}
primaryKey ( string | array | null $key = null ) : string | array Returns the primary key field name or sets a new one
query ( ) {@inheritDoc}
registryAlias ( string | null $registryAlias = null ) : string Returns the table registry key used to create this table instance
removeBehavior ( string $name ) : void Removes a behavior from this table's behavior registry.
save ( Cake\Datasource\EntityInterface $entity, $options = [] ) {@inheritDoc}
saveMany ( array | Cake\ORM\ResultSet $entities, array | ArrayAccess $options = [] ) : boolean | array | Cake\ORM\ResultSet Persists multiple entities of a table.
schema ( array | Cake\Database\Schema\Table | null $schema = null ) : Cake\Database\Schema\Table Returns the schema table object describing this table's properties.
table ( string | null $table = null ) : string Returns the database table name or sets a new one
updateAll ( $fields, $conditions ) {@inheritDoc}
validateUnique ( mixed $value, array $options, array $context = null ) : boolean Validator method used to check the uniqueness of a value for a column.

Protected Methods

Method Description
_dynamicFinder ( string $method, array $args ) : mixed Provides the dynamic findBy and findByAll methods.
_getFindOrCreateQuery ( array | Query | string $search ) : Query Gets the query object for findOrCreate().
_initializeSchema ( Cake\Database\Schema\Table $table ) : Cake\Database\Schema\Table Override this function in order to alter the schema used by this table.
_insert ( Cake\Datasource\EntityInterface $entity, array $data ) : Cake\Datasource\EntityInterface | boolean Auxiliary function to handle the insert of an entity's data in the table
_newId ( array $primary ) : mixed Generate a primary key value for a new record.
_onSaveSuccess ( Cake\Datasource\EntityInterface $entity, ArrayObject $options ) : boolean Handles the saving of children associations and executing the afterSave logic once the entity for this table has been saved successfully.
_processDelete ( Cake\Datasource\EntityInterface $entity, ArrayObject $options ) : boolean Perform the delete operation.
_processFindOrCreate ( array | callable $search, callable $callback = null, array $options = [] ) : Cake\Datasource\EntityInterface Performs the actual find and/or create of an entity based on the passed options.
_processSave ( Cake\Datasource\EntityInterface $entity, ArrayObject $options ) : Cake\Datasource\EntityInterface | boolean Performs the actual saving of an entity based on the passed options.
_setFieldMatchers ( array $options, array $keys ) : array Out of an options array, check if the keys described in $keys are arrays and change the values for closures that will concatenate the each of the properties in the value array when passed a row.
_update ( Cake\Datasource\EntityInterface $entity, array $data ) : Cake\Datasource\EntityInterface | boolean Auxiliary function to handle the update of an entity's data in the table

Method Details

__call() public method

If your Table uses any behaviors you can call them as if they were on the table object.
public __call ( string $method, array $args ) : mixed
$method string name of the method to be invoked
$args array List of arguments passed to the function
return mixed

__construct() public method

The $config array understands the following keys: - table: Name of the database table to represent - alias: Alias to be assigned to this table (default to table name) - connection: The connection instance to use - entityClass: The fully namespaced class name of the entity class that will represent rows in this table. - schema: A \Cake\Database\Schema\Table object or an array that can be passed to it. - eventManager: An instance of an event manager to use for internal events - behaviors: A BehaviorRegistry. Generally not used outside of tests. - associations: An AssociationCollection instance. - validator: A Validator instance which is assigned as the "default" validation set, or an associative array, where key is the name of the validation set and value the Validator instance.
public __construct ( array $config = [] )
$config array List of options for this table

__debugInfo() public method

Returns an array that can be used to describe the internal state of this object.
public __debugInfo ( ) : array
return array

__get() public method

Returns the association named after the passed value if exists, otherwise throws an exception.
public __get ( string $property ) : Cake\ORM\Association
$property string the association name
return Cake\ORM\Association

__isset() public method

Returns whether an association named after the passed value exists for this table.
public __isset ( string $property ) : boolean
$property string the association name
return boolean

_dynamicFinder() protected method

Provides the dynamic findBy and findByAll methods.
protected _dynamicFinder ( string $method, array $args ) : mixed
$method string The method name that was fired.
$args array List of arguments passed to the function.
return mixed

_getFindOrCreateQuery() protected method

Gets the query object for findOrCreate().
protected _getFindOrCreateQuery ( array | Query | string $search ) : Query
$search array | Query | string The criteria to find existing records by.
return Query

_initializeSchema() protected method

This function is only called after fetching the schema out of the database. If you wish to provide your own schema to this table without touching the database, you can override schema() or inject the definitions though that method. ### Example: protected function _initializeSchema(\Cake\Database\Schema\Table $table) { $table->columnType('preferences', 'json'); return $table; }
protected _initializeSchema ( Cake\Database\Schema\Table $table ) : Cake\Database\Schema\Table
$table Cake\Database\Schema\Table The table definition fetched from database.
return Cake\Database\Schema\Table the altered schema

_insert() protected method

Auxiliary function to handle the insert of an entity's data in the table
protected _insert ( Cake\Datasource\EntityInterface $entity, array $data ) : Cake\Datasource\EntityInterface | boolean
$entity Cake\Datasource\EntityInterface the subject entity from were $data was extracted
$data array The actual data that needs to be saved
return Cake\Datasource\EntityInterface | boolean

_newId() protected method

By default, this uses the type system to generate a new primary key value if possible. You can override this method if you have specific requirements for id generation.
protected _newId ( array $primary ) : mixed
$primary array The primary key columns to get a new ID for.
return mixed Either null or the new primary key value.

_onSaveSuccess() protected method

Handles the saving of children associations and executing the afterSave logic once the entity for this table has been saved successfully.
protected _onSaveSuccess ( Cake\Datasource\EntityInterface $entity, ArrayObject $options ) : boolean
$entity Cake\Datasource\EntityInterface the entity to be saved
$options ArrayObject the options to use for the save operation
return boolean True on success

_processDelete() protected method

Will delete the entity provided. Will remove rows from any dependent associations, and clear out join tables for BelongsToMany associations.
protected _processDelete ( Cake\Datasource\EntityInterface $entity, ArrayObject $options ) : boolean
$entity Cake\Datasource\EntityInterface The entity to delete.
$options ArrayObject The options for the delete.
return boolean success

_processFindOrCreate() protected method

Performs the actual find and/or create of an entity based on the passed options.
protected _processFindOrCreate ( array | callable $search, callable $callback = null, array $options = [] ) : Cake\Datasource\EntityInterface
$search array | callable The criteria to find an existing record by, or a callable tha will customize the find query.
$callback callable A callback that will be invoked for newly created entities. This callback will be called *before* the entity is persisted.
$options array The options to use when saving.
return Cake\Datasource\EntityInterface An entity.

_processSave() protected method

Performs the actual saving of an entity based on the passed options.
protected _processSave ( Cake\Datasource\EntityInterface $entity, ArrayObject $options ) : Cake\Datasource\EntityInterface | boolean
$entity Cake\Datasource\EntityInterface the entity to be saved
$options ArrayObject the options to use for the save operation
return Cake\Datasource\EntityInterface | boolean

_setFieldMatchers() protected method

This is an auxiliary function used for result formatters that can accept composite keys when comparing values.
protected _setFieldMatchers ( array $options, array $keys ) : array
$options array the original options passed to a finder
$keys array the keys to check in $options to build matchers from the associated value
return array

_update() protected method

Auxiliary function to handle the update of an entity's data in the table
protected _update ( Cake\Datasource\EntityInterface $entity, array $data ) : Cake\Datasource\EntityInterface | boolean
$entity Cake\Datasource\EntityInterface the subject entity from were $data was extracted
$data array The actual data that needs to be saved
return Cake\Datasource\EntityInterface | boolean

addAssociations() public method

It takes an array containing set of table names indexed by association type as argument: $this->Posts->addAssociations([ 'belongsTo' => [ 'Users' => ['className' => 'App\Model\Table\UsersTable'] ], 'hasMany' => ['Comments'], 'belongsToMany' => ['Tags'] ]); Each association type accepts multiple associations where the keys are the aliases, and the values are association config data. If numeric keys are used the values will be treated as association aliases.
See also: Cake\ORM\Table::belongsTo()
See also: Cake\ORM\Table::hasOne()
See also: Cake\ORM\Table::hasMany()
See also: Cake\ORM\Table::belongsToMany()
public addAssociations ( array $params ) : void
$params array Set of associations to bind (indexed by association type)
return void

addBehavior() public method

Adds a behavior to this table's behavior collection. Behaviors provide an easy way to create horizontally re-usable features that can provide trait like functionality, and allow for events to be listened to. Example: Load a behavior, with some settings. $this->addBehavior('Tree', ['parent' => 'parentId']); Behaviors are generally loaded during Table::initialize().
See also: Cake\ORM\Behavior
public addBehavior ( string $name, array $options = [] ) : void
$name string The name of the behavior. Can be a short class reference.
$options array The options for the behavior to use.
return void

alias() public method

{@inheritDoc}
public alias ( $alias = null )

aliasField() public method

If field is already aliased it will result in no-op.
public aliasField ( string $field ) : string
$field string The field to alias.
return string The field prefixed with the table alias.

association() public method

Returns an association object configured for the specified alias if any
public association ( string $name ) : Cake\ORM\Association | null
$name string the alias used for the association.
return Cake\ORM\Association | null Either the association or null.

associations() public method

Get the associations collection for this table.
public associations ( ) : Cake\ORM\AssociationCollection
return Cake\ORM\AssociationCollection The collection of association objects.

behaviors() public method

Returns the behavior registry for this table.
public behaviors ( ) : Cake\ORM\BehaviorRegistry
return Cake\ORM\BehaviorRegistry The BehaviorRegistry instance.

belongsTo() public method

Target table can be inferred by its name, which is provided in the first argument, or you can either pass the to be instantiated or an instance of it directly. The options array accept the following keys: - className: The class name of the target table object - targetTable: An instance of a table object to be used as the target table - foreignKey: The name of the field to use as foreign key, if false none will be used - conditions: array with a list of conditions to filter the join with - joinType: The type of join to be used (e.g. INNER) - strategy: The loading strategy to use. 'join' and 'select' are supported. - finder: The finder method to use when loading records from this association. Defaults to 'all'. When the strategy is 'join', only the fields, containments, and where conditions will be used from the finder. This method will return the association object that was built.
public belongsTo ( string $associated, array $options = [] ) : Cake\ORM\Association\BelongsTo
$associated string the alias for the target table. This is used to uniquely identify the association
$options array list of options to configure the association definition
return Cake\ORM\Association\BelongsTo

belongsToMany() public method

Target table can be inferred by its name, which is provided in the first argument, or you can either pass the class name to be instantiated or an instance of it directly. The options array accept the following keys: - className: The class name of the target table object. - targetTable: An instance of a table object to be used as the target table. - foreignKey: The name of the field to use as foreign key. - targetForeignKey: The name of the field to use as the target foreign key. - joinTable: The name of the table representing the link between the two - through: If you choose to use an already instantiated link table, set this key to a configured Table instance containing associations to both the source and target tables in this association. - dependent: Set to false, if you do not want junction table records removed when an owning record is removed. - cascadeCallbacks: Set to true if you want CakePHP to fire callbacks on cascaded deletes. If false the ORM will use deleteAll() to remove data. When true join/junction table records will be loaded and then deleted. - conditions: array with a list of conditions to filter the join with. - sort: The order in which results for this association should be returned. - strategy: The strategy to be used for selecting results Either 'select' or 'subquery'. If subquery is selected the query used to return results in the source table will be used as conditions for getting rows in the target table. - saveStrategy: Either 'append' or 'replace'. Indicates the mode to be used for saving associated entities. The former will only create new links between both side of the relation and the latter will do a wipe and replace to create the links between the passed entities when saving. - strategy: The loading strategy to use. 'select' and 'subquery' are supported. - finder: The finder method to use when loading records from this association. Defaults to 'all'. This method will return the association object that was built.
public belongsToMany ( string $associated, array $options = [] ) : BelongsToMany
$associated string the alias for the target table. This is used to uniquely identify the association
$options array list of options to configure the association definition
return Cake\ORM\Association\BelongsToMany

buildRules() public method

{@inheritDoc}
public buildRules ( Cake\ORM\RulesChecker $rules ) : Cake\ORM\RulesChecker
$rules Cake\ORM\RulesChecker The rules object to be modified.
return Cake\ORM\RulesChecker

callFinder() public method

Calls a finder method directly and applies it to the passed query, if no query is passed a new one will be created and returned
public callFinder ( string $type, Query $query, array $options = [] ) : Query
$type string name of the finder to be called
$query Query The query object to apply the finder options to
$options array List of options to pass to the finder
return Query

connection() public method

Returns the connection instance or sets a new one
public connection ( Cake\Datasource\ConnectionInterface $conn = null ) : Cake\Datasource\ConnectionInterface
$conn Cake\Datasource\ConnectionInterface The new connection instance
return Cake\Datasource\ConnectionInterface

defaultConnectionName() public static method

This method is used to get the fallback connection name if an instance is created through the TableRegistry without a connection.
See also: Cake\ORM\TableRegistry::get()
public static defaultConnectionName ( ) : string
return string

delete() public method

For HasMany and HasOne associations records will be removed based on the dependent option. Join table records in BelongsToMany associations will always be removed. You can use the cascadeCallbacks option when defining associations to change how associated data is deleted. ### Options - atomic Defaults to true. When true the deletion happens within a transaction. - checkRules Defaults to true. Check deletion rules before deleting the record. ### Events - Model.beforeDelete Fired before the delete occurs. If stopped the delete will be aborted. Receives the event, entity, and options. - Model.afterDelete Fired after the delete has been successful. Receives the event, entity, and options. - Model.afterDeleteCommit Fired after the transaction is committed for an atomic delete. Receives the event, entity, and options. The options argument will be converted into an \ArrayObject instance for the duration of the callbacks, this allows listeners to modify the options used in the delete operation.
public delete ( Cake\Datasource\EntityInterface $entity, $options = [] )
$entity Cake\Datasource\EntityInterface

deleteAll() public method

{@inheritDoc}
public deleteAll ( $conditions )

displayField() public method

Returns the display field or sets a new one
public displayField ( string | null $key = null ) : string
$key string | null sets a new name to be used as display field
return string

entityClass() public method

Returns the class used to hydrate rows for this table or sets a new one
public entityClass ( string | null $name = null ) : string
$name string | null the name of the class to use
return string

exists() public method

{@inheritDoc}
public exists ( $conditions )

find() public method

### Model.beforeFind event Each find() will trigger a Model.beforeFind event for all attached listeners. Any listener can set a valid result set using $query By default, $options will recognize the following keys: - fields - conditions - order - limit - offset - page - group - having - contain - join ### Usage Using the options array: $query = $articles->find('all', [ 'conditions' => ['published' => 1], 'limit' => 10, 'contain' => ['Users', 'Comments'] ]); Using the builder interface: $query = $articles->find() ->where(['published' => 1]) ->limit(10) ->contain(['Users', 'Comments']); ### Calling finders The find() method is the entry point for custom finder methods. You can invoke a finder by specifying the type: $query = $articles->find('published'); Would invoke the findPublished method.
public find ( $type = 'all', $options = [] ) : Query
return Query The query builder

findAll() public method

By default findAll() applies no conditions, you can override this method in subclasses to modify how find('all') works.
public findAll ( Query $query, array $options ) : Query
$query Query The query to find with
$options array The options to use for the find
return Query The query builder

findList() public method

When calling this finder, the fields passed are used to determine what should be used as the array key, value and optionally what to group the results by. By default the primary key for the model is used for the key, and the display field as value. The results of this finder will be in the following form: [ 1 => 'value for id 1', 2 => 'value for id 2', 4 => 'value for id 4' ] You can specify which property will be used as the key and which as value by using the $options array, when not specified, it will use the results of calling primaryKey and displayField respectively in this table: $table->find('list', [ 'keyField' => 'name', 'valueField' => 'age' ]); Results can be put together in bigger groups when they share a property, you can customize the property to use for grouping by setting groupField: $table->find('list', [ 'groupField' => 'category_id', ]); When using a groupField results will be returned in this format: [ 'group_1' => [ 1 => 'value for id 1', 2 => 'value for id 2', ] 'group_2' => [ 4 => 'value for id 4' ] ]
public findList ( Query $query, array $options ) : Query
$query Query The query to find with
$options array The options for the find
return Query The query builder

findOrCreate() public method

A find() will be done to locate an existing record using the attributes defined in $search. If records matches the conditions, the first record will be returned. If no record can be found, a new entity will be created with the $search properties. If a callback is provided, it will be called allowing you to define additional default values. The new entity will be saved and returned. If your find conditions require custom order, associations or conditions, then the $search parameter can be a callable that takes the Query as the argument, or a \Cake\ORM\Query object passed as the $search parameter. Allowing you to customize the find results. ### Options The options array is passed to the save method with exception to the following keys: - atomic: Whether to execute the methods for find, save and callbacks inside a database transaction (default: true) - defaults: Whether to use the search criteria as default values for the new entity (default: true)
public findOrCreate ( array | Query $search, callable $callback = null, array $options = [] ) : Cake\Datasource\EntityInterface
$search array | Query The criteria to find existing records by. Note that when you pass a query object you'll have to use the 2nd arg of the method to modify the entity data before saving.
$callback callable A callback that will be invoked for newly created entities. This callback will be called *before* the entity is persisted.
$options array The options to use when saving.
return Cake\Datasource\EntityInterface An entity.

findThreaded() public method

Values belonging to a parent row based on their parent_id value will be recursively nested inside the parent row values using the children property You can customize what fields are used for nesting results, by default the primary key and the parent_id fields are used. If you wish to change these defaults you need to provide the keys keyField, parentField or nestingKey in $options: $table->find('threaded', [ 'keyField' => 'id', 'parentField' => 'ancestor_id' 'nestingKey' => 'children' ]);
public findThreaded ( Query $query, array $options ) : Query
$query Query The query to find with
$options array The options to find with
return Query The query builder

get() public method

### Usage Get an article and some relationships: $article = $articles->get(1, ['contain' => ['Users', 'Comments']]);
public get ( $primaryKey, $options = [] )

getSaveOptionsBuilder() public method

Gets a SaveOptionsBuilder instance.
public getSaveOptionsBuilder ( array $options = [] ) : Cake\ORM\SaveOptionsBuilder
$options array Options to parse by the builder.
return Cake\ORM\SaveOptionsBuilder

hasBehavior() public method

Check if a behavior with the given alias has been loaded.
public hasBehavior ( string $name ) : boolean
$name string The behavior alias to check.
return boolean Whether or not the behavior exists.

hasField() public method

Delegates to the schema object and checks for column presence using the Schema\Table instance.
public hasField ( string $field ) : boolean
$field string The field to check for.
return boolean True if the field exists, false if it does not.

hasFinder() public method

Returns true if the finder exists for the table
public hasFinder ( string $type ) : boolean
$type string name of finder to check
return boolean

hasMany() public method

Target table can be inferred by its name, which is provided in the first argument, or you can either pass the class name to be instantiated or an instance of it directly. The options array accept the following keys: - className: The class name of the target table object - targetTable: An instance of a table object to be used as the target table - foreignKey: The name of the field to use as foreign key, if false none will be used - dependent: Set to true if you want CakePHP to cascade deletes to the associated table when an entity is removed on this table. The delete operation on the associated table will not cascade further. To get recursive cascades enable cascadeCallbacks as well. Set to false if you don't want CakePHP to remove associated data, or when you are using database constraints. - cascadeCallbacks: Set to true if you want CakePHP to fire callbacks on cascaded deletes. If false the ORM will use deleteAll() to remove data. When true records will be loaded and then deleted. - conditions: array with a list of conditions to filter the join with - sort: The order in which results for this association should be returned - saveStrategy: Either 'append' or 'replace'. When 'append' the current records are appended to any records in the database. When 'replace' associated records not in the current set will be removed. If the foreign key is a null able column or if dependent is true records will be orphaned. - strategy: The strategy to be used for selecting results Either 'select' or 'subquery'. If subquery is selected the query used to return results in the source table will be used as conditions for getting rows in the target table. - finder: The finder method to use when loading records from this association. Defaults to 'all'. This method will return the association object that was built.
public hasMany ( string $associated, array $options = [] ) : Cake\ORM\Association\HasMany
$associated string the alias for the target table. This is used to uniquely identify the association
$options array list of options to configure the association definition
return Cake\ORM\Association\HasMany

hasOne() public method

Target table can be inferred by its name, which is provided in the first argument, or you can either pass the class name to be instantiated or an instance of it directly. The options array accept the following keys: - className: The class name of the target table object - targetTable: An instance of a table object to be used as the target table - foreignKey: The name of the field to use as foreign key, if false none will be used - dependent: Set to true if you want CakePHP to cascade deletes to the associated table when an entity is removed on this table. The delete operation on the associated table will not cascade further. To get recursive cascades enable cascadeCallbacks as well. Set to false if you don't want CakePHP to remove associated data, or when you are using database constraints. - cascadeCallbacks: Set to true if you want CakePHP to fire callbacks on cascaded deletes. If false the ORM will use deleteAll() to remove data. When true records will be loaded and then deleted. - conditions: array with a list of conditions to filter the join with - joinType: The type of join to be used (e.g. LEFT) - strategy: The loading strategy to use. 'join' and 'select' are supported. - finder: The finder method to use when loading records from this association. Defaults to 'all'. When the strategy is 'join', only the fields, containments, and where conditions will be used from the finder. This method will return the association object that was built.
public hasOne ( string $associated, array $options = [] ) : Cake\ORM\Association\HasOne
$associated string the alias for the target table. This is used to uniquely identify the association
$options array list of options to configure the association definition
return Cake\ORM\Association\HasOne

implementedEvents() public method

By implementing the conventional methods a table class is assumed to be interested in the related event. Override this method if you need to add non-conventional event listeners. Or if you want you table to listen to non-standard events. The conventional method map is: - Model.beforeMarshal => beforeMarshal - Model.buildValidator => buildValidator - Model.beforeFind => beforeFind - Model.beforeSave => beforeSave - Model.afterSave => afterSave - Model.afterSaveCommit => afterSaveCommit - Model.beforeDelete => beforeDelete - Model.afterDelete => afterDelete - Model.afterDeleteCommit => afterDeleteCommit - Model.beforeRules => beforeRules - Model.afterRules => afterRules
public implementedEvents ( ) : array
return array

initialize() public method

You can use this method to define associations, attach behaviors define validation and do any other initialization logic you need. public function initialize(array $config) { $this->belongsTo('Users'); $this->belongsToMany('Tagging.Tags'); $this->primaryKey('something_else'); }
public initialize ( array $config ) : void
$config array Configuration options passed to the constructor
return void

loadInto() public method

### Example: $user = $usersTable->get(1); $user = $usersTable->loadInto($user, ['Articles.Tags', 'Articles.Comments']); echo $user->articles[0]->title; You can also load associations for multiple entities at once ### Example: $users = $usersTable->find()->where([...])->toList(); $users = $usersTable->loadInto($users, ['Articles.Tags', 'Articles.Comments']); echo $user[1]->articles[0]->title; The properties for the associations to be loaded will be overwritten on each entity.
See also: Cake\ORM\Query::contain()
public loadInto ( Cake\Datasource\EntityInterface | array $entities, array $contain ) : Cake\Datasource\EntityInterface | array
$entities Cake\Datasource\EntityInterface | array a single entity or list of entities
$contain array A `contain()` compatible array.
return Cake\Datasource\EntityInterface | array

marshaller() public method

Override this method if you want a table object to use custom marshalling logic.
See also: Cake\ORM\Marshaller
public marshaller ( ) : Cake\ORM\Marshaller
return Cake\ORM\Marshaller

newEntities() public method

By default all the associations on this table will be hydrated. You can limit which associations are built, or include deeper associations using the options parameter: $articles = $this->Articles->newEntities( $this->request->data(), ['associated' => ['Tags', 'Comments.Users']] ); You can limit fields that will be present in the constructed entities by passing the fieldList option, which is also accepted for associations: $articles = $this->Articles->newEntities($this->request->data(), [ 'fieldList' => ['title', 'body', 'tags', 'comments'], 'associated' => ['Tags', 'Comments.Users' => ['fieldList' => 'username']] ] ); You can use the Model.beforeMarshal event to modify request data before it is converted into entities.
public newEntities ( array $data, array $options = [] )
$data array
$options array

newEntity() public method

By default all the associations on this table will be hydrated. You can limit which associations are built, or include deeper associations using the options parameter: $article = $this->Articles->newEntity( $this->request->data(), ['associated' => ['Tags', 'Comments.Users']] ); You can limit fields that will be present in the constructed entity by passing the fieldList option, which is also accepted for associations: $article = $this->Articles->newEntity($this->request->data(), [ 'fieldList' => ['title', 'body', 'tags', 'comments'], 'associated' => ['Tags', 'Comments.Users' => ['fieldList' => 'username']] ] ); The fieldList option lets remove or restrict input data from ending up in the entity. If you'd like to relax the entity's default accessible fields, you can use the accessibleFields option: $article = $this->Articles->newEntity( $this->request->data(), ['accessibleFields' => ['protected_field' => true]] ); By default, the data is validated before being passed to the new entity. In the case of invalid fields, those will not be present in the resulting object. The validate option can be used to disable validation on the passed data: $article = $this->Articles->newEntity( $this->request->data(), ['validate' => false] ); You can also pass the name of the validator to use in the validate option. If null is passed to the first param of this function, no validation will be performed. You can use the Model.beforeMarshal event to modify request data before it is converted into entities.
public newEntity ( $data = null, array $options = [] )
$options array

patchEntities() public method

Those entries in $entities that cannot be matched to any record in $data will be discarded. Records in $data that could not be matched will be marshalled as a new entity. When merging HasMany or BelongsToMany associations, all the entities in the $data array will appear, those that can be matched by primary key will get the data merged, but those that cannot, will be discarded. You can limit fields that will be present in the merged entities by passing the fieldList option, which is also accepted for associations: $articles = $this->Articles->patchEntities($articles, $this->request->data(), [ 'fieldList' => ['title', 'body', 'tags', 'comments'], 'associated' => ['Tags', 'Comments.Users' => ['fieldList' => 'username']] ] ); You can use the Model.beforeMarshal event to modify request data before it is converted into entities.
public patchEntities ( $entities, array $data, array $options = [] )
$data array
$options array

patchEntity() public method

When merging HasMany or BelongsToMany associations, all the entities in the $data array will appear, those that can be matched by primary key will get the data merged, but those that cannot, will be discarded. You can limit fields that will be present in the merged entity by passing the fieldList option, which is also accepted for associations: $article = $this->Articles->patchEntity($article, $this->request->data(), [ 'fieldList' => ['title', 'body', 'tags', 'comments'], 'associated' => ['Tags', 'Comments.Users' => ['fieldList' => 'username']] ] ); By default, the data is validated before being passed to the entity. In the case of invalid fields, those will not be assigned to the entity. The validate option can be used to disable validation on the passed data: $article = $this->patchEntity($article, $this->request->data(),[ 'validate' => false ]); You can use the Model.beforeMarshal event to modify request data before it is converted into entities.
public patchEntity ( Cake\Datasource\EntityInterface $entity, array $data, array $options = [] )
$entity Cake\Datasource\EntityInterface
$data array
$options array

primaryKey() public method

Returns the primary key field name or sets a new one
public primaryKey ( string | array | null $key = null ) : string | array
$key string | array | null sets a new name to be used as primary key
return string | array

query() public method

{@inheritDoc}
public query ( )

registryAlias() public method

Returns the table registry key used to create this table instance
public registryAlias ( string | null $registryAlias = null ) : string
$registryAlias string | null the key used to access this object
return string

removeBehavior() public method

Example: Remove a behavior from this table. $this->removeBehavior('Tree');
See also: Cake\ORM\Behavior
public removeBehavior ( string $name ) : void
$name string The alias that the behavior was added with.
return void

save() public method

### Options The options array accepts the following keys: - atomic: Whether to execute the save and callbacks inside a database transaction (default: true) - checkRules: Whether or not to check the rules on entity before saving, if the checking fails, it will abort the save operation. (default:true) - associated: If true it will save 1st level associated entities as they are found in the passed $entity whenever the property defined for the association is marked as dirty. If an array, it will be interpreted as the list of associations to be saved. It is possible to provide different options for saving on associated table objects using this key by making the custom options the array value. If false no associated records will be saved. (default: true) - checkExisting: Whether or not to check if the entity already exists, assuming that the entity is marked as not new, and the primary key has been set. ### Events When saving, this method will trigger four events: - Model.beforeRules: Will be triggered right before any rule checking is done for the passed entity if the checkRules key in $options is not set to false. Listeners will receive as arguments the entity, options array and the operation type. If the event is stopped the rules check result will be set to the result of the event itself. - Model.afterRules: Will be triggered right after the checkRules() method is called for the entity. Listeners will receive as arguments the entity, options array, the result of checking the rules and the operation type. If the event is stopped the checking result will be set to the result of the event itself. - Model.beforeSave: Will be triggered just before the list of fields to be persisted is calculated. It receives both the entity and the options as arguments. The options array is passed as an ArrayObject, so any changes in it will be reflected in every listener and remembered at the end of the event so it can be used for the rest of the save operation. Returning false in any of the listeners will abort the saving process. If the event is stopped using the event API, the event object's result property will be returned. This can be useful when having your own saving strategy implemented inside a listener. - Model.afterSave: Will be triggered after a successful insert or save, listeners will receive the entity and the options array as arguments. The type of operation performed (insert or update) can be determined by checking the entity's method isNew, true meaning an insert and false an update. - Model.afterSaveCommit: Will be triggered after the transaction is commited for atomic save, listeners will receive the entity and the options array as arguments. This method will determine whether the passed entity needs to be inserted or updated in the database. It does that by checking the isNew method on the entity. If the entity to be saved returns a non-empty value from its errors() method, it will not be saved. ### Saving on associated tables This method will by default persist entities belonging to associated tables, whenever a dirty property matching the name of the property name set for an association in this table. It is possible to control what associations will be saved and to pass additional option for saving them. Only save the comments association $articles->save($entity, ['associated' => ['Comments']); Save the company, the employees and related addresses for each of them. For employees do not check the entity rules $companies->save($entity, [ 'associated' => [ 'Employees' => [ 'associated' => ['Addresses'], 'checkRules' => false ] ] ]); Save no associations $articles->save($entity, ['associated' => false]);
public save ( Cake\Datasource\EntityInterface $entity, $options = [] )
$entity Cake\Datasource\EntityInterface

saveMany() public method

The records will be saved in a transaction which will be rolled back if any one of the records fails to save due to failed validation or database error.
public saveMany ( array | Cake\ORM\ResultSet $entities, array | ArrayAccess $options = [] ) : boolean | array | Cake\ORM\ResultSet
$entities array | Cake\ORM\ResultSet Entities to save.
$options array | ArrayAccess Options used when calling Table::save() for each entity.
return boolean | array | Cake\ORM\ResultSet False on failure, entities list on success.

schema() public method

If an \Cake\Database\Schema\Table is passed, it will be used for this table instead of the default one. If an array is passed, a new \Cake\Database\Schema\Table will be constructed out of it and used as the schema for this table.
public schema ( array | Cake\Database\Schema\Table | null $schema = null ) : Cake\Database\Schema\Table
$schema array | Cake\Database\Schema\Table | null New schema to be used for this table
return Cake\Database\Schema\Table

table() public method

Returns the database table name or sets a new one
public table ( string | null $table = null ) : string
$table string | null the new table name
return string

updateAll() public method

{@inheritDoc}
public updateAll ( $fields, $conditions )

validateUnique() public method

This is meant to be used with the validation API and not to be called directly. ### Example: $validator->add('email', [ 'unique' => ['rule' => 'validateUnique', 'provider' => 'table'] ]) Unique validation can be scoped to the value of another column: $validator->add('email', [ 'unique' => [ 'rule' => ['validateUnique', ['scope' => 'site_id']], 'provider' => 'table' ] ]); In the above example, the email uniqueness will be scoped to only rows having the same site_id. Scoping will only be used if the scoping field is present in the data to be validated.
public validateUnique ( mixed $value, array $options, array $context = null ) : boolean
$value mixed The value of column to be checked for uniqueness
$options array The options array, optionally containing the 'scope' key. May also be the validation context if there are no options.
$context array Either the validation context or null.
return boolean true if the value is unique

Property Details

$_alias protected property

Human name giving to this particular instance. Multiple objects representing the same database table can exist by using different aliases.
protected string $_alias
return string

$_associations protected property

The associations container for this Table.
protected AssociationCollection,Cake\ORM $_associations
return Cake\ORM\AssociationCollection

$_behaviors protected property

BehaviorRegistry for this table
protected BehaviorRegistry,Cake\ORM $_behaviors
return Cake\ORM\BehaviorRegistry

$_connection protected property

Connection instance
protected ConnectionInterface,Cake\Datasource $_connection
return Cake\Datasource\ConnectionInterface

$_displayField protected property

The name of the field that represents a human readable representation of a row
protected string $_displayField
return string

$_entityClass protected property

The name of the class that represent a single row for this table
protected string $_entityClass
return string

$_primaryKey protected property

The name of the field that represents the primary key in the table
protected string|array $_primaryKey
return string | array

$_registryAlias protected property

Registry key used to create this table object
protected string $_registryAlias
return string

$_schema protected property

The schema object containing a description of this table fields
protected Table,Cake\Database\Schema $_schema
return Cake\Database\Schema\Table

$_table protected property

Name of the table as it can be found in the database
protected string $_table
return string