Represents a single database 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.
The primary way to retrieve data is using Table::find(). See that method for more information.
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]'); 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.
Table objects emit several events during as life-cycle hooks during find, delete and save operations. All events use the CakePHP event package:
Model.beforeFind 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 this is the root query, or an associated query.
Model.buildValidator Allows listeners to modify validation rules for the provided named validator.
Model.buildRules Allows listeners to modify the rules checker by adding more rules.
Model.beforeRules 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.
Model.afterRules 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.
Model.beforeSave 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.
Model.afterSave Fired after an entity is saved.
Model.afterSaveCommit 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.
Model.beforeDelete Fired before an entity is deleted. By stopping this event you will abort the delete operation.
Model.afterDelete Fired after an entity has been deleted.
You can subscribe to the events listed above in your table classes by implementing the lifecycle methods below:
beforeFind(EventInterface $event, Query $query, ArrayObject $options, boolean $primary)beforeMarshal(EventInterface $event, ArrayObject $data, ArrayObject $options)afterMarshal(EventInterface $event, EntityInterface $entity, ArrayObject $options)buildValidator(EventInterface $event, Validator $validator, string $name)buildRules(RulesChecker $rules)beforeRules(EventInterface $event, EntityInterface $entity, ArrayObject $options, string $operation)afterRules(EventInterface $event, EntityInterface $entity, ArrayObject $options, bool $result, string $operation)beforeSave(EventInterface $event, EntityInterface $entity, ArrayObject $options)afterSave(EventInterface $event, EntityInterface $entity, ArrayObject $options)afterSaveCommit(EventInterface $event, EntityInterface $entity, ArrayObject $options)beforeDelete(EventInterface $event, EntityInterface $entity, ArrayObject $options)afterDelete(EventInterface $event, EntityInterface $entity, ArrayObject $options)afterDeleteCommit(EventInterface $event, EntityInterface $entity, ArrayObject $options)string 'Model.buildValidator'
The name of the event dispatched when a validator has been built.
string 'default'
Name of default validation set.
string IsUnique::class
The IsUnique class name that is used.
string RulesChecker::class
The rules class name that is used.
string 'table'
The alias this object is assigned to validators as.
string|nullHuman name giving to this particular instance. Multiple objects representing the same database table can exist by using different aliases.
Cake\ORM\AssociationCollectionThe associations container for this Table.
Cake\ORM\BehaviorRegistryBehaviorRegistry for this table
Cake\Database\Connection|nullConnection instance
array<string>|string|nullThe name of the field that represents a human-readable representation of a row
stringThe name of the class that represent a single row for this table
stringDefault class name for new event objects.
Cake\Event\EventManagerInterface|nullInstance of the Cake\Event\EventManager this object is using to dispatch inner events.
array<string>|string|nullThe name of the field that represents the primary key in the table
string|nullRegistry key used to create this table object
Cake\Datasource\RulesCheckerThe domain rules to be applied to entities saved by this table
Cake\Database\Schema\TableSchemaInterface|nullThe schema object containing a description of this table fields
string|nullName of the table as it can be found in the database
stringValidator class.
arrayCake\Validation\Validator>A list of validation objects indexed by name
Handles behavior delegation + dynamic finders.
Initializes a new instance
Returns an array that can be used to describe the internal state of this object.
Returns the association named after the passed value if exists, otherwise throws an exception.
Returns whether an association named after the passed value exists for this table.
Provides the dynamic findBy and findAllBy methods.
Handles the logic executing of a worker inside a transaction.
Gets the query object for findOrCreate().
Override this function in order to alter the schema used by this table. 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.
Auxiliary function to handle the insert of an entity's data in the table
Generate a primary key value for a new record.
Handles the saving of children associations and executing the afterSave logic once the entity for this table has been saved successfully.
Perform the delete operation.
Performs the actual find and/or create of an entity based on the passed options.
Performs the actual saving of an entity based on the passed options.
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.
Checks if the caller would have executed a commit on a transaction.
Auxiliary function to handle the update of an entity's data in the table
Setup multiple associations.
Add a behavior.
Adds an array of behaviors to the table's behavior collection.
Alias a field with the table's current alias.
Get the associations collection for this table.
Returns the behavior registry for this table.
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.
Creates a new BelongsToMany association between this table and a target table. A "belongs to many" association is a M-N relationship.
Returns a RulesChecker object after modifying the one that was supplied.
Calls a finder method and applies it to the passed query.
Checks if all table name + column name combinations used for queries fit into the max length allowed by database driver.
Returns whether the passed entity complies with all the rules stored in the rules checker.
Creates a validator using a custom method inside your class.
Get the default connection name.
Delete a single entity.
Deletes all records matching the provided conditions.
Deletes multiple entities of a table.
Deletes multiple entities of a table.
Try to delete an entity or throw a PersistenceFailedException if the entity is new, has no primary key value, application rules checks failed or the delete was aborted by a callback.
Wrapper for creating and dispatching events.
Returns true if there is any record in this repository matching the specified conditions.
Creates a new Query for this repository and applies some defaults based on the type of search that was selected.
Returns the query as passed.
Returns an association object configured for the specified alias if any.
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.
Finds an existing record or creates a new one.
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.
Returns a single record after finding it by its primary key, if no record is found this method throws an exception.
Returns the table alias.
Returns an association object configured for the specified alias.
Get a behavior from the registry.
Returns the connection instance.
Returns the display field.
Returns the class used to hydrate rows for this table.
Returns the Cake\Event\EventManager manager instance for this object.
Returns the primary key field name.
Returns the table registry key used to create this table instance.
Gets a SaveOptionsBuilder instance.
Returns the schema table object describing this table's properties.
Returns the database table name.
Returns the validation rules tagged with $name. It is possible to have multiple different named validation sets, this is useful when you need to use varying rules when saving from different routines in your system.
Checks whether a specific association exists on this Table instance.
Check if a behavior with the given alias has been loaded.
Test to see if a Table has a specific field/column.
Returns true if the finder exists for the table
Creates a new HasMany association between this table and a target table. A "has many" association is a 1-N relationship.
Creates a new HasOne association between this table and a target table. A "has one" association is a 1-1 relationship.
Checks whether a validator has been set.
Get the Model callbacks this table is interested in.
Initialize a table instance. Called after the constructor.
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.
Get the object used to marshal/convert array data into objects.
This creates a new entity object.
Create a list of entities + associated entities from an array.
Create a new entity + associated entities from an array.
Merges each of the elements passed in $data into the entities found in $entities respecting the accessible fields configured on the entities. Merging is done by matching the primary key in each of the elements in $data and $entities.
Merges the passed $data into $entity respecting the accessible fields configured on the entity. Returns the same entity after being altered.
Creates a new Query instance for a table.
Removes a behavior from this table's behavior registry.
Returns the RulesChecker for this instance.
Persists an entity based on the fields that are marked as dirty and returns the same entity after a successful save or false in case of any error.
Persists multiple entities of a table.
Persists multiple entities of a table.
Try to save an entity or throw a PersistenceFailedException if the application rules checks failed, the entity contains errors or the save was aborted by a callback.
Sets the table alias.
Sets the connection instance.
Sets the display field.
Sets the class used to hydrate rows for this table.
Returns the Cake\Event\EventManagerInterface instance for this object.
Sets the primary key field name.
Sets the table registry key used to create this table instance.
Sets the schema table object describing this table's properties.
Sets the database table name.
This method stores a custom validator under the given name.
Creates a new Query::subquery() instance for a table.
Update all matching records.
Validator method used to check the uniqueness of a value for a column. This is meant to be used with the validation API and not to be called directly.
Returns the default validator object. Subclasses can override this function to add a default validation set to the validator object.
Checks if validation method exists.
__call(string $method, array $args): mixed
Handles behavior delegation + dynamic finders.
If your Table uses any behaviors you can call them as if they were on the table object.
string $method name of the method to be invoked
array $args List of arguments passed to the function
mixedBadMethodCallException__construct(array<string, mixed> $config = [])
Initializes a new instance
The $config array understands the following keys:
array<string, mixed> $config optional List of options for this table
__debugInfo(): array<string, mixed>
Returns an array that can be used to describe the internal state of this object.
array<string, mixed>__get(string $property): Cake\ORM\Association
Returns the association named after the passed value if exists, otherwise throws an exception.
string $property the association name
Cake\ORM\AssociationRuntimeException__isset(string $property): bool
Returns whether an association named after the passed value exists for this table.
string $property the association name
bool_deleteMany(iterableCake\Datasource\EntityInterface> $entities, ArrayAccess|array $options = []): Cake\Datasource\EntityInterface|null
iterableCake\Datasource\EntityInterface> $entities Entities to delete.
ArrayAccess|array $options optional Options used.
Cake\Datasource\EntityInterface|null_dynamicFinder(string $method, array $args): Cake\ORM\Query
Provides the dynamic findBy and findAllBy methods.
string $method The method name that was fired.
array $args List of arguments passed to the function.
Cake\ORM\QueryBadMethodCallException_executeTransaction(callable $worker, bool $atomic = true): mixed
Handles the logic executing of a worker inside a transaction.
callable $worker The worker that will run inside the transaction.
bool $atomic optional Whether to execute the worker inside a database transaction.
mixed_getFindOrCreateQuery(Cake\ORM\Query|callable|array $search): Cake\ORM\Query
Gets the query object for findOrCreate().
Cake\ORM\Query|callable|array $search The criteria to find existing records by.
Cake\ORM\Query_initializeSchema(Cake\Database\Schema\TableSchemaInterface $schema): Cake\Database\Schema\TableSchemaInterface
Override this function in order to alter the schema used by this table. 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.
protected function _initializeSchema(\Cake\Database\Schema\TableSchemaInterface $schema) {
$schema->setColumnType('preferences', 'json');
return $schema;
} Cake\Database\Schema\TableSchemaInterface $schema The table definition fetched from database.
Cake\Database\Schema\TableSchemaInterface_insert(Cake\Datasource\EntityInterface $entity, array $data): Cake\Datasource\EntityInterface|false
Auxiliary function to handle the insert of an entity's data in the table
Cake\Datasource\EntityInterface $entity the subject entity from were $data was extracted
array $data The actual data that needs to be saved
Cake\Datasource\EntityInterface|falseRuntimeException_newId(array<string> $primary): string|null
Generate a primary key value for a new record.
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.
Note: The ORM will not generate primary key values for composite primary keys. You can overwrite _newId() in your table class.
array<string> $primary The primary key columns to get a new ID for.
string|null_onSaveSuccess(Cake\Datasource\EntityInterface $entity, ArrayObject $options): bool
Handles the saving of children associations and executing the afterSave logic once the entity for this table has been saved successfully.
Cake\Datasource\EntityInterface $entity the entity to be saved
ArrayObject $options the options to use for the save operation
boolCake\ORM\Exception\RolledbackTransactionException_processDelete(Cake\Datasource\EntityInterface $entity, ArrayObject $options): bool
Perform the delete operation.
Will delete the entity provided. Will remove rows from any dependent associations, and clear out join tables for BelongsToMany associations.
Cake\Datasource\EntityInterface $entity The entity to delete.
ArrayObject $options The options for the delete.
boolInvalidArgumentException_processFindOrCreate(Cake\ORM\Query|callable|array $search, callable|null $callback = null, array<string, mixed> $options = []): Cake\Datasource\EntityInterface|array
Performs the actual find and/or create of an entity based on the passed options.
Cake\ORM\Query|callable|array $search The criteria to find an existing record by, or a callable tha will customize the find query.
callable|null $callback optional A callback that will be invoked for newly created entities. This callback will be called before the entity is persisted.
array<string, mixed> $options optional The options to use when saving.
Cake\Datasource\EntityInterface|arrayCake\ORM\Exception\PersistenceFailedExceptionInvalidArgumentException_processSave(Cake\Datasource\EntityInterface $entity, ArrayObject $options): Cake\Datasource\EntityInterface|false
Performs the actual saving of an entity based on the passed options.
Cake\Datasource\EntityInterface $entity the entity to be saved
ArrayObject $options the options to use for the save operation
Cake\Datasource\EntityInterface|falseRuntimeExceptionCake\ORM\Exception\RolledbackTransactionException_saveMany(iterableCake\Datasource\EntityInterface> $entities, Cake\ORM\SaveOptionsBuilderArrayAccess|array $options = []): iterableCake\Datasource\EntityInterface>
iterableCake\Datasource\EntityInterface> $entities Entities to save.
Cake\ORM\SaveOptionsBuilderArrayAccess|array $options optional Options used when calling Table::save() for each entity.
iterableCake\Datasource\EntityInterface>Cake\ORM\Exception\PersistenceFailedExceptionException_setFieldMatchers(array<string, mixed> $options, array<string> $keys): array<string, mixed>
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.
This is an auxiliary function used for result formatters that can accept composite keys when comparing values.
array<string, mixed> $options the original options passed to a finder
array<string> $keys the keys to check in $options to build matchers from the associated value
array<string, mixed>_transactionCommitted(bool $atomic, bool $primary): bool
Checks if the caller would have executed a commit on a transaction.
bool $atomic True if an atomic transaction was used.
bool $primary True if a primary was used.
bool_update(Cake\Datasource\EntityInterface $entity, array $data): Cake\Datasource\EntityInterface|false
Auxiliary function to handle the update of an entity's data in the table
Cake\Datasource\EntityInterface $entity the subject entity from were $data was extracted
array $data The actual data that needs to be saved
Cake\Datasource\EntityInterface|falseInvalidArgumentExceptionaddAssociations(array $params): $this
Setup multiple associations.
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.
array $params Set of associations to bind (indexed by association type)
$thisaddBehavior(string $name, array<string, mixed> $options = []): $this
Add a behavior.
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().
string $name The name of the behavior. Can be a short class reference.
array<string, mixed> $options optional The options for the behavior to use.
$thisRuntimeExceptionaddBehaviors(array $behaviors): $this
Adds an array of behaviors to the table's behavior collection.
Example:
$this->addBehaviors([
'Timestamp',
'Tree' => ['level' => 'level'],
]); array $behaviors All the behaviors to load.
$thisRuntimeExceptionaliasField(string $field): string
Alias a field with the table's current alias.
If field is already aliased it will result in no-op.
string $field The field to alias.
stringassociations(): Cake\ORM\AssociationCollection
Get the associations collection for this table.
Cake\ORM\AssociationCollectionbehaviors(): Cake\ORM\BehaviorRegistry
Returns the behavior registry for this table.
Cake\ORM\BehaviorRegistrybelongsTo(string $associated, array<string, mixed> $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.
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:
This method will return the association object that was built.
string $associated the alias for the target table. This is used to uniquely identify the association
array<string, mixed> $options optional list of options to configure the association definition
Cake\ORM\Association\BelongsTobelongsToMany(string $associated, array<string, mixed> $options = []): Cake\ORM\Association\BelongsToMany
Creates a new BelongsToMany association between this table and a target table. A "belongs to many" association is a M-N relationship.
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:
This method will return the association object that was built.
string $associated the alias for the target table. This is used to uniquely identify the association
array<string, mixed> $options optional list of options to configure the association definition
Cake\ORM\Association\BelongsToManybuildRules(Cake\Datasource\RulesChecker $rules): Cake\ORM\RulesChecker
Returns a RulesChecker object after modifying the one that was supplied.
Subclasses should override this method in order to initialize the rules to be applied to entities saved by this instance.
Cake\Datasource\RulesChecker $rules The rules object to be modified.
Cake\ORM\RulesCheckercallFinder(string $type, Cake\ORM\Query $query, array<string, mixed> $options = []): Cake\ORM\Query
Calls a finder method and applies it to the passed query.
string $type Name of the finder to be called.
Cake\ORM\Query $query The query object to apply the finder options to.
array<string, mixed> $options optional List of options to pass to the finder.
Cake\ORM\QueryBadMethodCallExceptioncheckAliasLengths(): void
Checks if all table name + column name combinations used for queries fit into the max length allowed by database driver.
voidRuntimeExceptioncheckRules(Cake\Datasource\EntityInterface $entity, string $operation = RulesChecker::CREATE, ArrayObject|array|null $options = null): bool
Returns whether the passed entity complies with all the rules stored in the rules checker.
Cake\Datasource\EntityInterface $entity The entity to check for validity.
string $operation optional The operation being run. Either 'create', 'update' or 'delete'.
ArrayObject|array|null $options optional The options To be passed to the rules.
boolcreateValidator(string $name): Cake\Validation\Validator
Creates a validator using a custom method inside your class.
This method is used only to build a new validator and it does not store it in your object. If you want to build and reuse validators, use getValidator() method instead.
string $name The name of the validation set to create.
Cake\Validation\ValidatorRuntimeExceptiondefaultConnectionName(): string
Get the default connection name.
This method is used to get the fallback connection name if an instance is created through the TableLocator without a connection.
stringdelete(Cake\Datasource\EntityInterface $entity, ArrayAccess|array $options = []): bool
Delete a single entity.
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.
atomic Defaults to true. When true the deletion happens within a transaction.checkRules Defaults to true. Check deletion rules before deleting the record.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.
Cake\Datasource\EntityInterface $entity The entity to remove.
ArrayAccess|array $options optional The options for the delete.
booldeleteAll(mixed $conditions): int
Deletes all records matching the provided conditions.
This method will not trigger beforeDelete/afterDelete events. If you need those first load a collection of records and delete them.
This method will not execute on associations' cascade attribute. You should use database foreign keys + ON CASCADE rules if you need cascading deletes combined with this method.
mixed $conditions intdeleteMany(iterableCake\Datasource\EntityInterface> $entities, ArrayAccess|array $options = []): iterableCake\Datasource\EntityInterface>|false
Deletes multiple entities of a table.
The records will be deleted in a transaction which will be rolled back if any one of the records fails to delete due to failed validation or database error.
iterableCake\Datasource\EntityInterface> $entities Entities to delete.
ArrayAccess|array $options optional Options used when calling Table::save() for each entity.
iterableCake\Datasource\EntityInterface>|falsedeleteManyOrFail(iterableCake\Datasource\EntityInterface> $entities, ArrayAccess|array $options = []): iterableCake\Datasource\EntityInterface>
Deletes multiple entities of a table.
The records will be deleted in a transaction which will be rolled back if any one of the records fails to delete due to failed validation or database error.
iterableCake\Datasource\EntityInterface> $entities Entities to delete.
ArrayAccess|array $options optional Options used when calling Table::save() for each entity.
iterableCake\Datasource\EntityInterface>Cake\ORM\Exception\PersistenceFailedExceptiondeleteOrFail(Cake\Datasource\EntityInterface $entity, ArrayAccess|array $options = []): true
Try to delete an entity or throw a PersistenceFailedException if the entity is new, has no primary key value, application rules checks failed or the delete was aborted by a callback.
Cake\Datasource\EntityInterface $entity The entity to remove.
ArrayAccess|array $options optional The options for the delete.
trueCake\ORM\Exception\PersistenceFailedExceptiondispatchEvent(string $name, array|null $data = null, object|null $subject = null): Cake\Event\EventInterface
Wrapper for creating and dispatching events.
Returns a dispatched event.
string $name Name of the event.
array|null $data optional Any value you wish to be transported with this event to it can be read by listeners.
object|null $subject optional The object that this event applies to ($this by default).
Cake\Event\EventInterfaceexists(array $conditions): bool
Returns true if there is any record in this repository matching the specified conditions.
array $conditions boolfind(string $type = 'all', array<string, mixed> $options = []): Cake\ORM\Query
Creates a new Query for this repository and applies some defaults based on the type of search that was selected.
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:
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']);
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.
string $type optional the type of query to perform
array<string, mixed> $options optional An array that will be passed to Query::applyOptions()
Cake\ORM\QueryfindAll(Cake\ORM\Query $query, array<string, mixed> $options): Cake\ORM\Query
Returns the query as passed.
By default findAll() applies no conditions, you can override this method in subclasses to modify how find('all') works.
Cake\ORM\Query $query The query to find with
array<string, mixed> $options The options to use for the find
Cake\ORM\QueryfindAssociation(string $name): Cake\ORM\Association|null
Returns an association object configured for the specified alias if any.
The name argument also supports dot syntax to access deeper associations.
$users = $this->getAssociation('Articles.Comments.Users'); string $name The alias used for the association.
Cake\ORM\Association|nullfindList(Cake\ORM\Query $query, array<string, mixed> $options): Cake\ORM\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.
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'
]); The valueField can also be an array, in which case you can also specify the valueSeparator option to control how the values will be concatenated:
$table->find('list', [
'valueField' => ['first_name', 'last_name'],
'valueSeparator' => ' | ',
]); The results of this finder will be in the following form:
[ 1 => 'John | Doe', 2 => 'Steve | Smith' ]
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'
]
] Cake\ORM\Query $query The query to find with
array<string, mixed> $options The options for the find
Cake\ORM\QueryfindOrCreate(Cake\ORM\Query|callable|array $search, callable|null $callback = null, array<string, mixed> $options = []): Cake\Datasource\EntityInterface
Finds an existing record or creates a new one.
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.
The options array is passed to the save method with exception to the following keys:
Cake\ORM\Query|callable|array $search 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.
callable|null $callback optional A callback that will be invoked for newly created entities. This callback will be called before the entity is persisted.
array<string, mixed> $options optional The options to use when saving.
Cake\Datasource\EntityInterfaceCake\ORM\Exception\PersistenceFailedExceptionfindThreaded(Cake\ORM\Query $query, array<string, mixed> $options): Cake\ORM\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.
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'
]); Cake\ORM\Query $query The query to find with
array<string, mixed> $options The options to find with
Cake\ORM\Queryget(mixed $primaryKey, array<string, mixed> $options = []): Cake\Datasource\EntityInterface
Returns a single record after finding it by its primary key, if no record is found this method throws an exception.
Get an article and some relationships:
$article = $articles->get(1, ['contain' => ['Users', 'Comments']]);
mixed $primaryKey primary key value to find
array<string, mixed> $options optional options accepted by Table::find()
Cake\Datasource\EntityInterfaceCake\Datasource\Exception\RecordNotFoundExceptionCake\Datasource\Exception\InvalidPrimaryKeyExceptiongetAlias(): string
Returns the table alias.
stringgetAssociation(string $name): Cake\ORM\Association
Returns an association object configured for the specified alias.
The name argument also supports dot syntax to access deeper associations.
$users = $this->getAssociation('Articles.Comments.Users'); Note that this method requires the association to be present or otherwise throws an exception. If you are not sure, use hasAssociation() before calling this method.
string $name The alias used for the association.
Cake\ORM\AssociationInvalidArgumentExceptiongetBehavior(string $name): Cake\ORM\Behavior
Get a behavior from the registry.
string $name The behavior alias to get from the registry.
Cake\ORM\BehaviorInvalidArgumentExceptiongetConnection(): Cake\Database\Connection
Returns the connection instance.
Cake\Database\ConnectiongetDisplayField(): array<string>|string|null
Returns the display field.
array<string>|string|nullgetEntityClass(): string
Returns the class used to hydrate rows for this table.
stringgetEventManager(): Cake\Event\EventManagerInterface
Returns the Cake\Event\EventManager manager instance for this object.
You can use this instance to register any new listeners or callbacks to the object events, or create your own events and trigger them at will.
Cake\Event\EventManagerInterfacegetPrimaryKey(): array<string>|string
Returns the primary key field name.
array<string>|stringgetRegistryAlias(): string
Returns the table registry key used to create this table instance.
stringgetSaveOptionsBuilder(array<string, mixed> $options = []): Cake\ORM\SaveOptionsBuilder
Gets a SaveOptionsBuilder instance.
array<string, mixed> $options optional Options to parse by the builder.
Cake\ORM\SaveOptionsBuildergetSchema(): Cake\Database\Schema\TableSchemaInterface
Returns the schema table object describing this table's properties.
Cake\Database\Schema\TableSchemaInterfacegetTable(): string
Returns the database table name.
This can include the database schema name if set using setTable().
stringgetValidator(string|null $name = null): Cake\Validation\Validator
Returns the validation rules tagged with $name. It is possible to have multiple different named validation sets, this is useful when you need to use varying rules when saving from different routines in your system.
If a validator has not been set earlier, this method will build a valiator using a method inside your class.
For example, if you wish to create a validation set called 'forSubscription', you will need to create a method in your Table subclass as follows:
public function validationForSubscription($validator)
{
return $validator
->add('email', 'valid-email', ['rule' => 'email'])
->add('password', 'valid', ['rule' => 'notBlank'])
->requirePresence('username');
}
$validator = $this->getValidator('forSubscription'); You can implement the method in validationDefault in your Table subclass should you wish to have a validation set that applies in cases where no other set is specified.
If a $name argument has not been provided, the default validator will be returned. You can configure your default validator name in a DEFAULT_VALIDATOR class constant.
string|null $name optional The name of the validation set to return.
Cake\Validation\ValidatorhasAssociation(string $name): bool
Checks whether a specific association exists on this Table instance.
The name argument also supports dot syntax to access deeper associations.
$hasUsers = $this->hasAssociation('Articles.Comments.Users'); string $name The alias used for the association.
boolhasBehavior(string $name): bool
Check if a behavior with the given alias has been loaded.
string $name The behavior alias to check.
boolhasField(string $field): bool
Test to see if a Table has a specific field/column.
Delegates to the schema object and checks for column presence using the Schema\Table instance.
string $field The field to check for.
boolhasFinder(string $type): bool
Returns true if the finder exists for the table
string $type name of finder to check
boolhasMany(string $associated, array<string, mixed> $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.
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:
cascadeCallbacks as well. Set to false if you don't want CakePHP to remove associated data, or when you are using database constraints.dependent is true records will be orphaned.This method will return the association object that was built.
string $associated the alias for the target table. This is used to uniquely identify the association
array<string, mixed> $options optional list of options to configure the association definition
Cake\ORM\Association\HasManyhasOne(string $associated, array<string, mixed> $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.
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:
cascadeCallbacks as well. Set to false if you don't want CakePHP to remove associated data, or when you are using database constraints.This method will return the association object that was built.
string $associated the alias for the target table. This is used to uniquely identify the association
array<string, mixed> $options optional list of options to configure the association definition
Cake\ORM\Association\HasOnehasValidator(string $name): bool
Checks whether a validator has been set.
string $name The name of a validator.
boolimplementedEvents(): array<string, mixed>
Get the Model callbacks this table is interested in.
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:
array<string, mixed>initialize(array<string, mixed> $config): void
Initialize a table instance. Called after the constructor.
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->setPrimaryKey('something_else');
} array<string, mixed> $config Configuration options passed to the constructor
voidloadInto(Cake\Datasource\EntityInterface|arrayCake\Datasource\EntityInterface> $entities, array $contain): Cake\Datasource\EntityInterface|arrayCake\Datasource\EntityInterface>
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.
$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
$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.
Cake\Datasource\EntityInterface|arrayCake\Datasource\EntityInterface> $entities a single entity or list of entities
array $contain A contain() compatible array.
Cake\Datasource\EntityInterface|arrayCake\Datasource\EntityInterface>marshaller(): Cake\ORM\Marshaller
Get the object used to marshal/convert array data into objects.
Override this method if you want a table object to use custom marshalling logic.
Cake\ORM\MarshallernewEmptyEntity(): Cake\Datasource\EntityInterface
This creates a new entity object.
Careful: This does not trigger any field validation. This entity can be persisted without validation error as empty record. Always patch in required fields before saving.
Cake\Datasource\EntityInterfacenewEntities(array $data, array<string, mixed> $options = []): arrayCake\Datasource\EntityInterface>
Create a list of entities + associated entities from an array.
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->getData(), ['associated' => ['Tags', 'Comments.Users']] );
You can limit fields that will be present in the constructed entities by passing the fields option, which is also accepted for associations:
$articles = $this->Articles->newEntities($this->request->getData(), [ 'fields' => ['title', 'body', 'tags', 'comments'], 'associated' => ['Tags', 'Comments.Users' => ['fields' => 'username']] ] );
You can use the Model.beforeMarshal event to modify request data before it is converted into entities.
array $data The data to build an entity with.
array<string, mixed> $options optional A list of options for the objects hydration.
arrayCake\Datasource\EntityInterface>newEntity(array $data, array<string, mixed> $options = []): Cake\Datasource\EntityInterface
Create a new entity + associated entities from an array.
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->getData(), ['associated' => ['Tags', 'Comments.Users']] );
You can limit fields that will be present in the constructed entity by passing the fields option, which is also accepted for associations:
$article = $this->Articles->newEntity($this->request->getData(), [ 'fields' => ['title', 'body', 'tags', 'comments'], 'associated' => ['Tags', 'Comments.Users' => ['fields' => 'username']] ] );
The fields 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->getData(), ['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->getData(), ['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.
array $data The data to build an entity with.
array<string, mixed> $options optional A list of options for the object hydration.
Cake\Datasource\EntityInterfacepatchEntities(iterableCake\Datasource\EntityInterface> $entities, array $data, array<string, mixed> $options = []): arrayCake\Datasource\EntityInterface>
Merges each of the elements passed in $data into the entities found in $entities respecting the accessible fields configured on the entities. Merging is done by matching the primary key in each of the elements in $data and $entities.
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 fields option, which is also accepted for associations:
$articles = $this->Articles->patchEntities($articles, $this->request->getData(), [ 'fields' => ['title', 'body', 'tags', 'comments'], 'associated' => ['Tags', 'Comments.Users' => ['fields' => 'username']] ] );
You can use the Model.beforeMarshal event to modify request data before it is converted into entities.
iterableCake\Datasource\EntityInterface> $entities the entities that will get the data merged in
array $data list of arrays to be merged into the entities
array<string, mixed> $options optional A list of options for the objects hydration.
arrayCake\Datasource\EntityInterface>patchEntity(Cake\Datasource\EntityInterface $entity, array $data, array<string, mixed> $options = []): Cake\Datasource\EntityInterface
Merges the passed $data into $entity respecting the accessible fields configured on the entity. Returns the same entity after being altered.
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 fields option, which is also accepted for associations:
$article = $this->Articles->patchEntity($article, $this->request->getData(), [ 'fields' => ['title', 'body', 'tags', 'comments'], 'associated' => ['Tags', 'Comments.Users' => ['fields' => 'username']] ] );
$article = $this->Articles->patchEntity($article, $this->request->getData(), [
'associated' => [
'Tags' => ['accessibleFields' => ['*' => true]]
]
]); 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->getData(),[ 'validate' => false ]);
You can use the Model.beforeMarshal event to modify request data before it is converted into entities.
When patching scalar values (null/booleans/string/integer/float), if the property presently has an identical value, the setter will not be called, and the property will not be marked as dirty. This is an optimization to prevent unnecessary field updates when persisting entities.
Cake\Datasource\EntityInterface $entity the entity that will get the data merged in
array $data key value list of fields to be merged into the entity
array<string, mixed> $options optional A list of options for the object hydration.
Cake\Datasource\EntityInterfacequery(): Cake\ORM\Query
Creates a new Query instance for a table.
Cake\ORM\QueryremoveBehavior(string $name): $this
Removes a behavior from this table's behavior registry.
Example:
Remove a behavior from this table.
$this->removeBehavior('Tree'); string $name The alias that the behavior was added with.
$thisrulesChecker(): Cake\Datasource\RulesChecker
Returns the RulesChecker for this instance.
A RulesChecker object is used to test an entity for validity on rules that may involve complex logic or data that needs to be fetched from relevant datasources.
Cake\Datasource\RulesCheckersave(Cake\Datasource\EntityInterface $entity, ArrayAccess|array $options = []): Cake\Datasource\EntityInterface|false
Persists an entity based on the fields that are marked as dirty and returns the same entity after a successful save or false in case of any error.
The options array accepts the following keys:
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)When saving, this method will trigger four events:
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.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.result property will be returned. This can be useful when having your own saving strategy implemented inside a listener.isNew, true meaning an insert and false an update.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.
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]); Cake\Datasource\EntityInterface $entity the entity to be saved
ArrayAccess|array $options optional The options to use when saving.
Cake\Datasource\EntityInterface|falseCake\ORM\Exception\RolledbackTransactionExceptionsaveMany(iterableCake\Datasource\EntityInterface> $entities, Cake\ORM\SaveOptionsBuilderArrayAccess|array $options = []): iterableCake\Datasource\EntityInterface>|false
Persists multiple entities of a table.
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.
iterableCake\Datasource\EntityInterface> $entities Entities to save.
Cake\ORM\SaveOptionsBuilderArrayAccess|array $options optional Options used when calling Table::save() for each entity.
iterableCake\Datasource\EntityInterface>|falseExceptionsaveManyOrFail(iterableCake\Datasource\EntityInterface> $entities, ArrayAccess|array $options = []): iterableCake\Datasource\EntityInterface>
Persists multiple entities of a table.
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.
iterableCake\Datasource\EntityInterface> $entities Entities to save.
ArrayAccess|array $options optional Options used when calling Table::save() for each entity.
iterableCake\Datasource\EntityInterface>ExceptionCake\ORM\Exception\PersistenceFailedExceptionsaveOrFail(Cake\Datasource\EntityInterface $entity, ArrayAccess|array $options = []): Cake\Datasource\EntityInterface
Try to save an entity or throw a PersistenceFailedException if the application rules checks failed, the entity contains errors or the save was aborted by a callback.
Cake\Datasource\EntityInterface $entity the entity to be saved
ArrayAccess|array $options optional The options to use when saving.
Cake\Datasource\EntityInterfaceCake\ORM\Exception\PersistenceFailedExceptionsetAlias(string $alias): $this
Sets the table alias.
string $alias Table alias
$thissetConnection(Cake\Database\Connection $connection): $this
Sets the connection instance.
Cake\Database\Connection $connection The connection instance
$thissetDisplayField(array<string>|string $field): $this
Sets the display field.
array<string>|string $field Name to be used as display field.
$thissetEntityClass(string $name): $this
Sets the class used to hydrate rows for this table.
string $name The name of the class to use
$thisCake\ORM\Exception\MissingEntityExceptionsetEventManager(Cake\Event\EventManagerInterface $eventManager): $this
Returns the Cake\Event\EventManagerInterface instance for this object.
You can use this instance to register any new listeners or callbacks to the object events, or create your own events and trigger them at will.
Cake\Event\EventManagerInterface $eventManager the eventManager to set
$thissetPrimaryKey(array<string>|string $key): $this
Sets the primary key field name.
array<string>|string $key Sets a new name to be used as primary key
$thissetRegistryAlias(string $registryAlias): $this
Sets the table registry key used to create this table instance.
string $registryAlias The key used to access this object.
$thissetSchema(Cake\Database\Schema\TableSchemaInterface|array $schema): $this
Sets the schema table object describing this table's properties.
If an array is passed, a new TableSchemaInterface will be constructed out of it and used as the schema for this table.
Cake\Database\Schema\TableSchemaInterface|array $schema Schema to be used for this table
$thissetTable(string $table): $this
Sets the database table name.
This can include the database schema name in the form 'schema.table'. If the name must be quoted, enable automatic identifier quoting.
string $table Table name.
$thissetValidator(string $name, Cake\Validation\Validator $validator): $this
This method stores a custom validator under the given name.
You can build the object by yourself and store it in your object:
$validator = new \Cake\Validation\Validator();
$validator
->add('email', 'valid-email', ['rule' => 'email'])
->add('password', 'valid', ['rule' => 'notBlank'])
->allowEmpty('bio');
$this->setValidator('forSubscription', $validator); string $name The name of a validator to be set.
Cake\Validation\Validator $validator Validator object to be set.
$thissubquery(): Cake\ORM\Query
Creates a new Query::subquery() instance for a table.
Cake\ORM\QueryupdateAll(Cake\Database\Expression\QueryExpressionClosure|array|string $fields, mixed $conditions): int
Update all matching records.
Sets the $fields to the provided values based on $conditions. This method will not trigger beforeSave/afterSave events. If you need those first load a collection of records and update them.
Cake\Database\Expression\QueryExpressionClosure|array|string $fields mixed $conditions intvalidateUnique(mixed $value, array<string, mixed> $options, array|null $context = null): bool
Validator method used to check the uniqueness of a value for a column. This is meant to be used with the validation API and not to be called directly.
$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.
mixed $value The value of column to be checked for uniqueness.
array<string, mixed> $options The options array, optionally containing the 'scope' key. May also be the validation context, if there are no options.
array|null $context optional Either the validation context or null.
boolvalidationDefault(Cake\Validation\Validator $validator): Cake\Validation\Validator
Returns the default validator object. Subclasses can override this function to add a default validation set to the validator object.
Cake\Validation\Validator $validator The validator that can be modified to add some rules to it.
Cake\Validation\ValidatorvalidationMethodExists(string $name): bool
Checks if validation method exists.
string $name boolHuman name giving to this particular instance. Multiple objects representing the same database table can exist by using different aliases.
string|nullThe associations container for this Table.
Cake\ORM\AssociationCollectionBehaviorRegistry for this table
Cake\ORM\BehaviorRegistryConnection instance
Cake\Database\Connection|nullThe name of the field that represents a human-readable representation of a row
array<string>|string|nullThe name of the class that represent a single row for this table
stringDefault class name for new event objects.
stringInstance of the Cake\Event\EventManager this object is using to dispatch inner events.
Cake\Event\EventManagerInterface|nullThe name of the field that represents the primary key in the table
array<string>|string|nullRegistry key used to create this table object
string|nullThe domain rules to be applied to entities saved by this table
Cake\Datasource\RulesCheckerThe schema object containing a description of this table fields
Cake\Database\Schema\TableSchemaInterface|nullName of the table as it can be found in the database
string|nullValidator class.
stringA list of validation objects indexed by name
arrayCake\Validation\Validator>
© 2005–present The Cake Software Foundation, Inc.
Licensed under the MIT License.
CakePHP is a registered trademark of Cake Software Foundation, Inc.
We are not endorsed by or affiliated with CakePHP.
https://api.cakephp.org/4.4/class-Cake.ORM.Table.html