Class Table
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.
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.
Events
Table objects emit several events during as life-cycle hooks during find, delete and save operations. All events use the CakePHP event package:
-
Model.beforeFindFired 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$primaryparameter indicates whether this is the root query, or an associated query. -
Model.buildValidatorAllows listeners to modify validation rules for the provided named validator. -
Model.buildRulesAllows listeners to modify the rules checker by adding more rules. Behaviors or custom listeners can subscribe to this event. For tables you don't need to subscribe to this event, simply override theTable::buildRules()method. -
Model.beforeRulesFired 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.afterRulesFired 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.beforeSaveFired 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.afterSaveFired after an entity is saved. -
Model.afterSaveCommitFired 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.beforeDeleteFired before an entity is deleted. By stopping this event you will abort the delete operation. -
Model.afterDeleteFired after an entity has been deleted.
Callbacks
You can subscribe to the events listed above in your table classes by implementing the lifecycle methods below:
beforeFind(EventInterface $event, SelectQuery $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)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)
See: \Cake\Event\EventManager for reference on the events system.
Link: https://book.cakephp.org/5/en/orm/table-objects.html#event-list
Constants
-
stringBUILD_VALIDATOR_EVENT ¶'Model.buildValidator'The name of the event dispatched when a validator has been built.
-
stringDEFAULT_VALIDATOR ¶'default'Name of default validation set.
-
class-string<Cake\ORM\Rule\IsUnique>IS_UNIQUE_CLASS ¶IsUnique::classThe IsUnique class name that is used.
-
class-string<Cake\ORM\RulesChecker>RULES_CLASS ¶RulesChecker::classThe rules class name that is used.
-
stringVALIDATOR_PROVIDER_NAME ¶'table'The alias this object is assigned to validators as.
Property Summary
-
$alias protected
string|nullHuman name giving to this particular instance. Multiple objects representing the same database table can exist by using different aliases.
-
$assertEntityClass protected
boolWhether to assert that entities passed to save/delete/patch/loadInto match the table's configured entity class. Disable per table via {@see Table::disableEntityClassAssertion()} when foreign entities are passed intentionally.
-
$associations protected
Cake\ORM\AssociationCollectionThe associations container for this Table.
-
$behaviors protected
Cake\ORM\BehaviorRegistryBehaviorRegistry for this table
-
$connection protected
Cake\Database\Connection|nullConnection instance
-
$displayField protected
array<string>|string|nullThe name of the field that represents a human-readable representation of a row
-
$entityClass protected
class-string<TEntity>|nullThe name of the class that represent a single row for this table
-
$eventClass protected
stringDefault class name for new event objects.
-
$eventManager protected
Cake\Event\EventManagerInterfaceInstance of the Cake\Event\EventManager this object is using to dispatch inner events.
-
$primaryKey protected
array<string>|string|nullThe name of the field that represents the primary key in the table
-
$queryFactory protected
QueryFactory -
$registryAlias protected
string|nullRegistry key used to create this table object
-
$rulesChecker protected
Cake\Datasource\RulesChecker|nullThe domain rules to be applied to entities saved by this table
-
$schema protected
Cake\Database\Schema\TableSchemaInterface|nullThe schema object containing a description of this table fields
-
$table protected
string|nullName of the table as it can be found in the database
-
$validatorClass protected
class-string<Cake\Validation\Validator>Validator class.
-
$validators protected
array<Cake\Validation\Validator>A list of validation objects indexed by name
Method Summary
-
__call() public
Handles behavior delegation + dynamic finders.
If your Table uses any behaviors you can call them as if they were on the table object.
-
__construct() public
Initializes a new instance
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\TableSchemaInterface 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.
-
__debugInfo() public
Returns an array that can be used to describe the internal state of this object.
-
__get() public
Returns the association named after the passed value if exists, otherwise throws an exception.
-
__isset() public
Returns whether an association named after the passed value exists for this table.
-
addAssociations() public
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.
-
addBehavior() public
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().
-
addBehaviors() public
Adds an array of behaviors to the table's behavior collection.
Example:
$this->addBehaviors([ 'Timestamp', 'Tree' => ['level' => 'level'], ]); -
aliasField() public
Alias a field with the table's current alias.
If field is already aliased, it will result in no-op.
-
assertEntityClass() protected
Asserts that the given entity belongs to this table instance.
The entity must either be an instance of the table's configured entity class, or an instance of the generic
\Cake\ORM\Entityclass. The generic class is allowed as an escape hatch for ad-hoc usage such as$table->delete(new Entity(['id' => 1])).Catches mistakes like
$this->Invoices->delete($orderEntity)where an entity from a different table is passed. -
associations() public
Get the associations collection for this table.
-
behaviors() public
Returns the behavior registry for this table.
-
belongsTo() public
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:
- 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.
-
belongsToMany() public
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:
- 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.
-
buildRules() public
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.
-
callFinder() public
Calls a finder method and applies it to the passed query.
-
checkAliasLengths() protected
Checks if all table name + column name combinations used for queries fit into the max length allowed by database driver.
-
checkRules() public
Returns whether the passed entity complies with all the rules stored in the rules checker.
-
createValidator() protected
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.
-
defaultConnectionName() public static
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.
-
delete() public
{@inheritDoc}
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
cascadeCallbacksoption when defining associations to change how associated data is deleted.Options
atomicDefaults to true. When true the deletion happens within a transaction.checkRulesDefaults to true. Check deletion rules before deleting the record.
Events
Model.beforeDeleteFired before the delete occurs. If stopped the delete will be aborted. Receives the event, entity, and options.Model.afterDeleteFired after the delete has been successful. Receives the event, entity, and options.Model.afterDeleteCommitFired 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.
-
deleteAll() public
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'
cascadeattribute. You should use database foreign keys + ON CASCADE rules if you need cascading deletes combined with this method. -
deleteMany() public
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.
-
deleteManyOrFail() public
Deletes multiple entities of a table or throws a PersistenceFailedException if any one of the records fails to delete.
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.
-
deleteOrFail() public
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.
-
deleteQuery() public
Creates a new delete query
-
disableEntityClassAssertion() public
Disables the entity-class assertion for this table. Use when foreign entities are passed intentionally (e.g. polymorphic patterns).
-
dispatchEvent() public
Wrapper for creating and dispatching events.
Returns a dispatched event.
-
doDeleteMany() protected
-
doSaveMany() protected
-
dynamicFinder() protected
Provides the dynamic findBy and findAllBy methods.
-
enableEntityClassAssertion() public
Enables the assertion that entities passed to save/delete/patch/loadInto match the table's configured entity class.
-
executeTransaction() protected
Handles the logic executing of a worker inside a transaction.
-
exists() public
Returns true if there is any record in this repository matching the specified conditions.
-
find() public
Creates a new Query for this repository and applies some defaults based on the type of search that was selected.
Model.beforeFind event
Each find() will trigger a
Model.beforeFindevent for all attached listeners. Any listener can set a valid result set using $queryBy default, following special named arguments are recognized which are used as select query options:
- fields
- conditions
- order
- limit
- offset
- page
- group
- having
- contain
- join
Usage
$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.
This will invoke the
findPublishedmethod:$query = $articles->find('published');Typed finder arguments
Finders must have a
SelectQueryinstance as their 1st argument and any additional parameters as needed.Here, the finder "findByCategory" has an integer
$categoryparameter:function findByCategory(SelectQuery $query, int $category): SelectQuery { return $query; }This finder can be called as:
$query = $articles->find('byCategory', $category);or using named arguments as:
$query = $articles->find(type: 'byCategory', category: $category); -
findAll() public
Returns the query as passed.
By default findAll() applies no query clauses, you can override this method in subclasses to modify how
find('all')works. -
findAssociation() protected
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'); -
findList() public
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, when not specified, it will use the results of calling
primaryKeyanddisplayFieldrespectively in this table:$table->find('list', keyField: 'name', valueField: 'age');The
valueFieldcan also be an array, in which case you can also specify thevalueSeparatoroption 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
groupFieldresults 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' ] ] -
findOrCreate() public
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\SelectQuery 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)
-
findThreaded() public
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
childrenpropertyYou can customize what fields are used for nesting results, by default the primary key and the
parent_idfields are used. If you wish to change these defaults you need to provide thekeyField,parentFieldornestingKeyarguments:$table->find('threaded', keyField: 'id', parentField: 'ancestor_id', nestingKey: 'children'); -
get() public
{@inheritDoc}
Usage
Get an article and some relationships:
$article = $articles->get(1, contain: ['Users', 'Comments']); -
getAlias() public
Returns the table alias.
-
getAssociation() public
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.
-
getBehavior() public
Get a behavior from the registry.
-
getConnection() public
Returns the connection instance.
-
getDisplayField() public
Returns the display field.
-
getEntityClass() public
Returns the class used to hydrate rows for this table.
-
getEventManager() public
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.
-
getFindOrCreateQuery() protected
Gets the query object for findOrCreate().
-
getPrimaryKey() public
Returns the primary key field name.
-
getRegistryAlias() public
Returns the table registry key used to create this table instance.
-
getSchema() public
Returns the schema table object describing this table's properties.
-
getTable() public
Returns the database table name.
This can include the database schema name if set using
setTable(). -
getValidator() public
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 validator 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
validationDefaultin 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_VALIDATORclass constant. -
hasAssociation() public
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'); -
hasBehavior() public
Check if a behavior with the given alias has been loaded.
-
hasField() public
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.
-
hasFinder() public
Returns true if the finder exists for the table
-
hasMany() public
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:
- 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
cascadeCallbacksas 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
dependentis 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.
-
hasOne() public
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:
- 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
cascadeCallbacksas 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.
-
hasValidator() public
Checks whether a validator has been set.
-
implementedEvents() public
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:
- Model.beforeMarshal => beforeMarshal
- Model.afterMarshal => afterMarshal
- 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
-
initialize() public
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'); } -
insert() protected
Auxiliary function to handle the insert of an entity's data in the table
-
insertQuery() public
Creates a new insert query
-
invokeFinder() protected
Invokes the finder callable with appropriate arguments.
-
isEntityClassAssertionEnabled() public
Returns whether the entity-class assertion is enabled for this table.
-
loadInto() public
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.
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.
-
marshaller() public
Get the object used to marshal/convert array data into objects.
Override this method if you want a table object to use custom marshaling logic.
-
newEmptyEntity() public
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.
-
newEntities() public
{@inheritDoc}
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
fieldsoption, 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.beforeMarshalevent to modify request data before it is converted into entities. -
newEntity() public
{@inheritDoc}
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
fieldsoption, 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
fieldsoption lets remove or restrict input data from ending up in the entity. If you'd like to relax the entity's default patchable fields, you can use thepatchableFieldsoption:$article = $this->Articles->newEntity( $this->request->getData(), ['patchableFields' => ['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
validateoption 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
validateoption. Ifnullis passed to the first param of this function, no validation will be performed.You can use the
Model.beforeMarshalevent to modify request data before it is converted into entities. -
newId() protected
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.
-
onSaveSuccess() protected
Handles the saving of children associations and executing the afterSave logic once the entity for this table has been saved successfully.
-
patchEntities() public
{@inheritDoc}
Those entries in
$entitiesthat cannot be matched to any record in$datawill be discarded. Records in$datathat could not be matched will be marshaled as a new entity.When merging HasMany or BelongsToMany associations, all the entities in the
$dataarray 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
fieldsoption, 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.beforeMarshalevent to modify request data before it is converted into entities. -
patchEntity() public
{@inheritDoc}
When merging HasMany or BelongsToMany associations, all the entities in the
$dataarray 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
fieldsoption, 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' => ['patchableFields' => ['*' => true]] ] ]);$article = $this->Articles->patchEntity($article, $this->request->getData(), [ 'associated' => ['Tags' => ['_joinData' => ['Users']]] ]);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
validateoption can be used to disable validation on the passed data:$article = $this->patchEntity($article, $this->request->getData(),[ 'validate' => false ]);You can use the
Model.beforeMarshalevent 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.
-
processDelete() protected
Perform the delete operation.
Will delete the entity provided. Will remove rows from any dependent associations, and clear out join tables for BelongsToMany associations.
-
processFindOrCreate() protected
Performs the actual find and/or create of an entity based on the passed options.
-
processSave() protected
Performs the actual saving of an entity based on the passed options.
-
query() public
Creates a new SelectQuery instance for a table.
-
removeBehavior() public
Removes a behavior from this table's behavior registry.
Example:
Remove a behavior from this table.
$this->removeBehavior('Tree'); -
resolveRuleProvider() public
Get the object and method that should be used to invoke a validation rule method.
Resolves rule methods provided by behaviors, when the behavior's
implementedMethodsconfig is set. The rule method name is matched against the configured alias keys, case-insensitively. -
rulesChecker() public
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.
-
save() public
{@inheritDoc}
Options
The options array accepts the following keys:
- atomic: Whether to execute the save and callbacks inside a database transaction (default: true)
- checkRules: Whether to check the rules on entity before saving, if the checking fails, it will abort the save operation. (default:true)
- associated: If
trueit will save 1st level associated entities as they are found in the passed$entitywhenever 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. Iffalseno associated records will be saved. (default:true) - checkExisting: Whether 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
checkRuleskey 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
resultproperty 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 committed 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
isNewmethod on the entity. If the entity to be saved returns a non-empty value from itserrors()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' => [ 'Addresses', 'checkRules' => false ] ] ]); // Save no associations $articles->save($entity, ['associated' => false]); -
saveMany() public
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.
-
saveManyOrFail() public
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.
-
saveOrFail() public
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.
-
selectQuery() public
Creates a new select query
-
setAlias() public
Sets the table alias.
-
setConnection() public
Sets the connection instance.
-
setDisplayField() public
Sets the display field.
-
setEntityClass() public
Sets the class used to hydrate rows for this table.
-
setEventManager() public
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.
-
setFieldMatchers() protected
Out of an options array, check if the keys described in
$keysare 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.
-
setPrimaryKey() public
Sets the primary key field name.
-
setRegistryAlias() public
Sets the table registry key used to create this table instance.
-
setSchema() public
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.
-
setTable() public
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.
-
setValidator() public
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); -
subquery() public
Creates a new Query instance with field auto aliasing disabled.
This is useful for subqueries.
-
transactionCommitted() protected
Checks if the caller would have executed a commit on a transaction.
-
unhydratedFind() public
Type-safe non-hydrated read. Equivalent in behavior to
find($type, ...)->disableHydration()but the type system knows the results are arrays rather than entities.Construction methods (where/join/order/contain/finders) behave the same as on a regular {@see SelectQuery}; only the result-fetch methods (first/firstOrFail/all/toArray/iteration) differ in shape.
$rows = $articlesTable->unhydratedFind()->where(['published' => true])->all(); // $rows: iterable<array<string, mixed>>Only finders that mutate and return the query they were given are supported here (the overwhelming majority). A finder that discards the passed query and returns a freshly built one (e.g. by delegating to
find()) cannot preserve the non-hydrating contract and triggers an exception rather than a silent hydrated result. -
unhydratedSelectQuery() public
Creates a new non-hydrating select query.
-
update() protected
Auxiliary function to handle the update of an entity's data in the table
-
updateAll() public
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.
-
updateQuery() public
Creates a new update query
-
validateUnique() public
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.
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.
-
validationDefault() public
Returns the default validator object. Subclasses can override this function to add a default validation set to the validator object.
-
validationMethodExists() protected
Checks if validation method exists.
Method Detail
__call() ¶ public
__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.
Parameters
-
string$method name of the method to be invoked
-
array$args List of arguments passed to the function
Returns
mixedThrows
BadMethodCallException__construct() ¶ public
__construct(array<string, mixed> $config = [])
Initializes a new instance
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\TableSchemaInterface 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.
Parameters
-
array<string, mixed>$config optional List of options for this table.
__debugInfo() ¶ public
__debugInfo(): array<string, mixed>
Returns an array that can be used to describe the internal state of this object.
Returns
array<string, mixed>__get() ¶ public
__get(string $property): Cake\ORM\Association
Returns the association named after the passed value if exists, otherwise throws an exception.
Parameters
-
string$property the association name
Returns
Cake\ORM\AssociationThrows
Cake\Database\Exception\DatabaseExceptionif no association with such name exists
__isset() ¶ public
__isset(string $property): bool
Returns whether an association named after the passed value exists for this table.
Parameters
-
string$property the association name
Returns
booladdAssociations() ¶ public
addAssociations(array<string, array<string|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.
Parameters
-
array<string, array<string|array>>$params Set of associations to bind (indexed by association type)
Returns
$thisSee Also
\Cake\ORM\Table::hasOne()
\Cake\ORM\Table::hasMany()
\Cake\ORM\Table::belongsToMany()
addBehavior() ¶ public
addBehavior(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().
Parameters
-
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.
Returns
$thisThrows
RuntimeExceptionIf a behavior is being reloaded.
See Also
addBehaviors() ¶ public
addBehaviors(array $behaviors): $this
Adds an array of behaviors to the table's behavior collection.
Example:
$this->addBehaviors([
'Timestamp',
'Tree' => ['level' => 'level'],
]);
Parameters
-
array$behaviors All the behaviors to load.
Returns
$thisThrows
RuntimeExceptionIf a behavior is being reloaded.
aliasField() ¶ public
aliasField(string $field): string
Alias a field with the table's current alias.
If field is already aliased, it will result in no-op.
Parameters
-
string$field The field to alias.
Returns
stringThe field prefixed with the table alias.
assertEntityClass() ¶ protected
assertEntityClass(Cake\Datasource\EntityInterface $entity): void
Asserts that the given entity belongs to this table instance.
The entity must either be an instance of the table's configured entity
class, or an instance of the generic \Cake\ORM\Entity class. The
generic class is allowed as an escape hatch for ad-hoc usage such as
$table->delete(new Entity(['id' => 1])).
Catches mistakes like $this->Invoices->delete($orderEntity) where
an entity from a different table is passed.
Parameters
-
Cake\Datasource\EntityInterface$entity The entity to validate.
Returns
voidThrows
InvalidArgumentExceptionWhen the entity does not match the configured entity class.
associations() ¶ public
associations(): Cake\ORM\AssociationCollection
Get the associations collection for this table.
Returns
Cake\ORM\AssociationCollectionThe collection of association objects.
behaviors() ¶ public
behaviors(): Cake\ORM\BehaviorRegistry
Returns the behavior registry for this table.
Returns
Cake\ORM\BehaviorRegistryThe BehaviorRegistry instance.
belongsTo() ¶ public
belongsTo(string $associated, array<string, mixed> $options = []): Cake\ORM\Association\BelongsTo<Cake\ORM\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.
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.
Parameters
-
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
Returns
Cake\ORM\Association\BelongsTo<Cake\ORM\Table>belongsToMany() ¶ public
belongsToMany(string $associated, array<string, mixed> $options = []): Cake\ORM\Association\BelongsToMany<Cake\ORM\Table>
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:
- 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.
Parameters
-
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
Returns
Cake\ORM\Association\BelongsToMany<Cake\ORM\Table>buildRules() ¶ public
buildRules(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.
Parameters
-
Cake\Datasource\RulesChecker$rules The rules object to be modified.
Returns
Cake\ORM\RulesCheckercallFinder() ¶ public
callFinder(string $type, Cake\ORM\Query\SelectQuery<TSubject> $query, mixed ...$args): Cake\ORM\Query\SelectQuery<TSubject>
Calls a finder method and applies it to the passed query.
Templates
TSubject
of (\Cake\Datasource\EntityInterface | array) Parameters
-
string$type Name of the finder to be called.
-
Cake\ORM\Query\SelectQuery<TSubject>$query The query object to apply the finder options to.
-
mixed...$args Arguments that match up to finder-specific parameters
Returns
Cake\ORM\Query\SelectQuery<TSubject>Throws
BadMethodCallExceptioncheckAliasLengths() ¶ protected
checkAliasLengths(): void
Checks if all table name + column name combinations used for queries fit into the max length allowed by database driver.
Returns
voidThrows
Cake\Database\Exception\DatabaseExceptionWhen an alias combination is too long
checkRules() ¶ public
checkRules(Cake\Datasource\EntityInterface $entity, string $operation = RulesChecker::CREATE, ArrayObject<string, mixed>|array|null $options = null): bool
Returns whether the passed entity complies with all the rules stored in the rules checker.
Parameters
-
Cake\Datasource\EntityInterface$entity The entity to check for validity.
-
string$operation optional The operation being run. Either 'create', 'update' or 'delete'.
-
ArrayObject<string, mixed>|array|null$options optional The options To be passed to the rules.
Returns
boolcreateValidator() ¶ protected
createValidator(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.
Parameters
-
string$name The name of the validation set to create.
Returns
Cake\Validation\ValidatorThrows
InvalidArgumentExceptiondefaultConnectionName() ¶ public static
defaultConnectionName(): 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.
Returns
stringSee Also
delete() ¶ public
delete(Cake\Datasource\EntityInterface $entity, array<string, mixed> $options = []): bool
{@inheritDoc}
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
atomicDefaults to true. When true the deletion happens within a transaction.checkRulesDefaults to true. Check deletion rules before deleting the record.
Events
Model.beforeDeleteFired before the delete occurs. If stopped the delete will be aborted. Receives the event, entity, and options.Model.afterDeleteFired after the delete has been successful. Receives the event, entity, and options.Model.afterDeleteCommitFired 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.
Parameters
-
Cake\Datasource\EntityInterface$entity The entity to remove.
-
array<string, mixed>$options optional The options for the delete.
Returns
boolsuccess
deleteAll() ¶ public
deleteAll(Cake\Database\ExpressionInterface|Closure|array|string|null $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.
Parameters
-
Cake\Database\ExpressionInterface|Closure|array|string|null$conditions Conditions to be used, accepts anything Query::where() can take.
Returns
intReturns the number of affected rows.
deleteMany() ¶ public
deleteMany(iterable<TDeletedEntity> $entities, array<string, mixed> $options = []): ($entities is array ? array<TDeletedEntity> : iterable<TDeletedEntity>)|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.
Templates
TDeletedEntity
of \Cake\Datasource\EntityInterface Parameters
-
iterable<TDeletedEntity>$entities Entities to delete.
-
array<string, mixed>$options optional Options used when calling Table::save() for each entity.
Returns
($entities is array ? array<TDeletedEntity> : iterable<TDeletedEntity>)|falseEntities list on success, false on failure.
See Also
deleteManyOrFail() ¶ public
deleteManyOrFail(iterable<Cake\Datasource\EntityInterface> $entities, array<string, mixed> $options = []): void
Deletes multiple entities of a table or throws a PersistenceFailedException if any one of the records fails to delete.
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.
Parameters
-
iterable<Cake\Datasource\EntityInterface>$entities Entities to delete.
-
array<string, mixed>$options optional Options used when calling Table::save() for each entity.
Returns
voidThrows
Cake\ORM\Exception\PersistenceFailedExceptionSee Also
deleteOrFail() ¶ public
deleteOrFail(Cake\Datasource\EntityInterface $entity, array<string, mixed> $options = []): void
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.
Parameters
-
Cake\Datasource\EntityInterface$entity The entity to remove.
-
array<string, mixed>$options optional The options for the delete.
Returns
voidThrows
Cake\ORM\Exception\PersistenceFailedExceptionSee Also
deleteQuery() ¶ public
deleteQuery(): Cake\ORM\Query\DeleteQuery
Creates a new delete query
Returns
Cake\ORM\Query\DeleteQuerydisableEntityClassAssertion() ¶ public
disableEntityClassAssertion(): $this
Disables the entity-class assertion for this table. Use when foreign entities are passed intentionally (e.g. polymorphic patterns).
Returns
$thisdispatchEvent() ¶ public
dispatchEvent(string $name, array $data = [], TSubject|null $subject = null): Cake\Event\EventInterface<TSubject>
Wrapper for creating and dispatching events.
Returns a dispatched event.
Templates
TSubject
of object = $this Parameters
-
string$name Name of the event.
-
array$data optional Any value you wish to be transported with this event to it can be read by listeners.
-
TSubject|null$subject optional The object that this event applies to ($this by default).
Returns
Cake\Event\EventInterface<TSubject>doDeleteMany() ¶ protected
doDeleteMany(iterable<Cake\Datasource\EntityInterface> $entities, array<string, mixed> $options = []): Cake\Datasource\EntityInterface|null
Parameters
-
iterable<Cake\Datasource\EntityInterface>$entities Entities to delete.
-
array<string, mixed>$options optional Options used.
Returns
Cake\Datasource\EntityInterface|nulldoSaveMany() ¶ protected
doSaveMany(iterable<TSavedEntity> $entities, array<string, mixed> $options = []): $entities is array ? array<TSavedEntity> : iterable<TSavedEntity>
Templates
TSavedEntity
of \Cake\Datasource\EntityInterface Parameters
-
iterable<TSavedEntity>$entities Entities to save.
-
array<string, mixed>$options optional Options used when calling Table::save() for each entity.
Returns
$entities is array ? array<TSavedEntity> : iterable<TSavedEntity>Entities list.
Throws
Cake\ORM\Exception\PersistenceFailedExceptionIf an entity couldn't be saved.
ExceptionIf an entity couldn't be saved.
dynamicFinder() ¶ protected
dynamicFinder(string $method, array $args): Cake\ORM\Query\SelectQuery<TEntity|array>
Provides the dynamic findBy and findAllBy methods.
Parameters
-
string$method The method name that was fired.
-
array$args List of arguments passed to the function.
Returns
Cake\ORM\Query\SelectQuery<TEntity|array>Throws
BadMethodCallExceptionwhen there are missing arguments, or when and & or are combined.
enableEntityClassAssertion() ¶ public
enableEntityClassAssertion(bool $enable = true): $this
Enables the assertion that entities passed to save/delete/patch/loadInto match the table's configured entity class.
Parameters
-
bool$enable optional Whether to enable. Defaults to true.
Returns
$thisexecuteTransaction() ¶ protected
executeTransaction(Closure(): mixed $worker, bool $atomic = true): mixed
Handles the logic executing of a worker inside a transaction.
Parameters
-
Closure(): mixed$worker The worker that will run inside the transaction.
-
bool$atomic optional Whether to execute the worker inside a database transaction.
Returns
mixedexists() ¶ public
exists(ExpressionInterface|Closure|array|string|null $conditions): bool
Returns true if there is any record in this repository matching the specified conditions.
Parameters
-
ExpressionInterface|Closure|array|string|null$conditions
Returns
boolfind() ¶ public
find(string $type = 'all', mixed ...$args): Cake\ORM\Query\SelectQuery<TEntity>
Creates a new Query for this repository and applies some defaults based on the type of search that was selected.
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, following special named arguments are recognized which are used as select query options:
- fields
- conditions
- order
- limit
- offset
- page
- group
- having
- contain
- join
Usage
$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.
This will invoke the findPublished method:
$query = $articles->find('published');
Typed finder arguments
Finders must have a SelectQuery instance as their 1st argument and any
additional parameters as needed.
Here, the finder "findByCategory" has an integer $category parameter:
function findByCategory(SelectQuery $query, int $category): SelectQuery
{
return $query;
}
This finder can be called as:
$query = $articles->find('byCategory', $category);
or using named arguments as:
$query = $articles->find(type: 'byCategory', category: $category);
Parameters
-
string$type optional the type of query to perform
-
mixed...$args Arguments that match up to finder-specific parameters
Returns
Cake\ORM\Query\SelectQuery<TEntity>The query builder
findAll() ¶ public
findAll(Cake\ORM\Query\SelectQuery<TEntity> $query): Cake\ORM\Query\SelectQuery<TEntity>
Returns the query as passed.
By default findAll() applies no query clauses, you can override this
method in subclasses to modify how find('all') works.
Parameters
-
Cake\ORM\Query\SelectQuery<TEntity>$query The query to find with
Returns
Cake\ORM\Query\SelectQuery<TEntity>The query builder
findAssociation() ¶ protected
findAssociation(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');
Parameters
-
string$name The alias used for the association.
Returns
Cake\ORM\Association|nullEither the association or null.
findList() ¶ public
findList(Cake\ORM\Query\SelectQuery<TEntity|array> $query, Closure|array|string|null $keyField = null, Closure|array|string|null $valueField = null, Closure|array|string|null $groupField = null, string $valueSeparator = ' '): Cake\ORM\Query\SelectQuery<TEntity|array>
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,
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'
]
]
Parameters
-
Cake\ORM\Query\SelectQuery<TEntity|array>$query The query to find with
-
Closure|array|string|null$keyField optional -
Closure|array|string|null$valueField optional -
Closure|array|string|null$groupField optional -
string$valueSeparator optional
Returns
Cake\ORM\Query\SelectQuery<TEntity|array>The query builder
findOrCreate() ¶ public
findOrCreate(Cake\ORM\Query\SelectQuery<TEntity|array>|callable|array $search, callable|array|null $callback = null, array<string, mixed> $options = []): TEntity
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\SelectQuery 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)
Parameters
-
Cake\ORM\Query\SelectQuery<TEntity|array>|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|array|null$callback optional An array of data key/value pairs or 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.
Returns
TEntityAn entity.
Throws
Cake\ORM\Exception\PersistenceFailedExceptionWhen the entity couldn't be saved
findThreaded() ¶ public
findThreaded(Cake\ORM\Query\SelectQuery<TEntity|array> $query, Closure|array|string|null $keyField = null, Closure|array|string $parentField = 'parent_id', string $nestingKey = 'children'): Cake\ORM\Query\SelectQuery<TEntity|array>
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 keyField, parentField or nestingKey
arguments:
$table->find('threaded', keyField: 'id', parentField: 'ancestor_id', nestingKey: 'children');
Parameters
-
Cake\ORM\Query\SelectQuery<TEntity|array>$query The query to find with
-
Closure|array|string|null$keyField optional The path to the key field.
-
Closure|array|string$parentField optional The path to the parent field.
-
string$nestingKey optional The key to nest children under.
Returns
Cake\ORM\Query\SelectQuery<TEntity|array>The query builder
get() ¶ public
get(mixed $primaryKey, string $finder = 'all', Psr\SimpleCache\CacheInterface|string|null $cache = null, Closure|string|null $cacheKey = null, mixed ...$args): TEntity
{@inheritDoc}
Usage
Get an article and some relationships:
$article = $articles->get(1, contain: ['Users', 'Comments']);
Parameters
-
mixed$primaryKey primary key value to find
-
string$finder optional The finder to use.
-
Psr\SimpleCache\CacheInterface|string|null$cache optional The cache config to use. Defaults to
null, i.e. no caching.-
Closure|string|null$cacheKey optional The cache key to use. If not provided one will be autogenerated if
$cacheis not null.-
mixed...$args Arguments that query options or finder specific parameters.
Returns
TEntityThrows
Cake\Datasource\Exception\RecordNotFoundExceptionif the record with such id could not be found
Cake\Datasource\Exception\InvalidPrimaryKeyExceptionWhen $primaryKey has an incorrect number of elements.
See Also
getAssociation() ¶ public
getAssociation(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.
Parameters
-
string$name The alias used for the association.
Returns
Cake\ORM\AssociationThe association.
Throws
InvalidArgumentExceptiongetBehavior() ¶ public
getBehavior(TName $name): TName is key-of<TBehaviors> ? TBehaviors[TName] : \Cake\ORM\Behavior
Get a behavior from the registry.
Templates
TName
of string Parameters
-
TName$name The behavior alias to get from the registry.
Returns
TName is key-of<TBehaviors> ? TBehaviors[TName] : \Cake\ORM\BehaviorThrows
InvalidArgumentExceptionIf the behavior does not exist.
getConnection() ¶ public
getConnection(): Cake\Database\Connection
Returns the connection instance.
Returns
Cake\Database\ConnectiongetDisplayField() ¶ public
getDisplayField(): array<string>|string
Returns the display field.
Returns
array<string>|stringgetEntityClass() ¶ public
getEntityClass(): class-string<TEntity>
Returns the class used to hydrate rows for this table.
Returns
class-string<TEntity>getEventManager() ¶ public
getEventManager(): 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.
Returns
Cake\Event\EventManagerInterfacegetFindOrCreateQuery() ¶ protected
getFindOrCreateQuery(Cake\ORM\Query\SelectQuery<TEntity|array>|callable|array $search): Cake\ORM\Query\SelectQuery<TEntity|array>
Gets the query object for findOrCreate().
Parameters
-
Cake\ORM\Query\SelectQuery<TEntity|array>|callable|array$search The criteria to find existing records by.
Returns
Cake\ORM\Query\SelectQuery<TEntity|array>getPrimaryKey() ¶ public
getPrimaryKey(): array<string>|string
Returns the primary key field name.
Returns
array<string>|stringgetRegistryAlias() ¶ public
getRegistryAlias(): string
Returns the table registry key used to create this table instance.
Returns
stringgetSchema() ¶ public
getSchema(): Cake\Database\Schema\TableSchemaInterface
Returns the schema table object describing this table's properties.
Returns
Cake\Database\Schema\TableSchemaInterfacegetTable() ¶ public
getTable(): string
Returns the database table name.
This can include the database schema name if set using setTable().
Returns
stringgetValidator() ¶ public
getValidator(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 validator 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.
Parameters
-
string|null$name optional The name of the validation set to return.
Returns
Cake\Validation\ValidatorhasAssociation() ¶ public
hasAssociation(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');
Parameters
-
string$name The alias used for the association.
Returns
boolhasBehavior() ¶ public
hasBehavior(string $name): bool
Check if a behavior with the given alias has been loaded.
Parameters
-
string$name The behavior alias to check.
Returns
boolWhether the behavior exists.
hasField() ¶ public
hasField(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.
Parameters
-
string$field The field to check for.
Returns
boolTrue if the field exists, false if it does not.
hasFinder() ¶ public
hasFinder(string $type): bool
Returns true if the finder exists for the table
Parameters
-
string$type name of finder to check
Returns
boolhasMany() ¶ public
hasMany(string $associated, array<string, mixed> $options = []): Cake\ORM\Association\HasMany<Cake\ORM\Table>
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:
- 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
cascadeCallbacksas 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
dependentis 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.
Parameters
-
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
Returns
Cake\ORM\Association\HasMany<Cake\ORM\Table>hasOne() ¶ public
hasOne(string $associated, array<string, mixed> $options = []): Cake\ORM\Association\HasOne<Cake\ORM\Table>
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:
- 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
cascadeCallbacksas 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.
Parameters
-
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
Returns
Cake\ORM\Association\HasOne<Cake\ORM\Table>hasValidator() ¶ public
hasValidator(string $name): bool
Checks whether a validator has been set.
Parameters
-
string$name The name of a validator.
Returns
boolimplementedEvents() ¶ public
implementedEvents(): 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:
- Model.beforeMarshal => beforeMarshal
- Model.afterMarshal => afterMarshal
- 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
Returns
array<string, mixed>initialize() ¶ public
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');
}
Parameters
-
array<string, mixed>$config Configuration options passed to the constructor
Returns
voidinsert() ¶ protected
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
Parameters
-
Cake\Datasource\EntityInterface$entity the subject entity from were $data was extracted
-
array$data The actual data that needs to be saved
Returns
Cake\Datasource\EntityInterface|falseThrows
Cake\Database\Exception\DatabaseExceptionif not all the primary keys where supplied or could be generated when the table has composite primary keys. Or when the table has no primary key.
insertQuery() ¶ public
insertQuery(): Cake\ORM\Query\InsertQuery
Creates a new insert query
Returns
Cake\ORM\Query\InsertQueryinvokeFinder() ¶ protected
invokeFinder(Closure $callable, Cake\ORM\Query\SelectQuery<TSubject> $query, array $args): Cake\ORM\Query\SelectQuery<TSubject>
Invokes the finder callable with appropriate arguments.
Templates
TSubject
of (\Cake\Datasource\EntityInterface | array) Parameters
-
Closure$callable Callable.
-
Cake\ORM\Query\SelectQuery<TSubject>$query The query object.
-
array$args Arguments for the callable.
Returns
Cake\ORM\Query\SelectQuery<TSubject>isEntityClassAssertionEnabled() ¶ public
isEntityClassAssertionEnabled(): bool
Returns whether the entity-class assertion is enabled for this table.
Returns
boolloadInto() ¶ public
loadInto(TEntity|array<TEntity> $entities, array $contain): $entities is array ? array<TEntity> : TEntity
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.
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.
Parameters
-
TEntity|array<TEntity>$entities a single entity or list of entities
-
array$contain A
contain()compatible array.
Returns
$entities is array ? array<TEntity> : TEntitySee Also
marshaller() ¶ public
marshaller(): Cake\ORM\Marshaller<TEntity>
Get the object used to marshal/convert array data into objects.
Override this method if you want a table object to use custom marshaling logic.
Returns
Cake\ORM\Marshaller<TEntity>See Also
newEmptyEntity() ¶ public
newEmptyEntity(): TEntity
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.
Returns
TEntitynewEntities() ¶ public
newEntities(array $data, array<string, mixed> $options = []): array<TEntity>
{@inheritDoc}
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.
Parameters
-
array$data The data to build an entity with.
-
array<string, mixed>$options optional A list of options for the objects hydration.
Returns
array<TEntity>An array of hydrated records.
newEntity() ¶ public
newEntity(array $data, array<string, mixed> $options = []): TEntity
{@inheritDoc}
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 patchable fields,
you can use the patchableFields option:
$article = $this->Articles->newEntity(
$this->request->getData(),
['patchableFields' => ['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.
Parameters
-
array$data The data to build an entity with.
-
array<string, mixed>$options optional A list of options for the object hydration.
Returns
TEntitySee Also
newId() ¶ protected
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.
Parameters
-
array<string>$primary The primary key columns to get a new ID for.
Returns
string|nullThe primary key value when a single primary key is available, or null.
onSaveSuccess() ¶ protected
onSaveSuccess(Cake\Datasource\EntityInterface $entity, ArrayObject<string, mixed> $options): bool
Handles the saving of children associations and executing the afterSave logic once the entity for this table has been saved successfully.
Parameters
-
Cake\Datasource\EntityInterface$entity the entity to be saved
-
ArrayObject<string, mixed>$options the options to use for the save operation
Returns
boolTrue on success
Throws
Cake\ORM\Exception\RolledbackTransactionExceptionIf the transaction is aborted in the afterSave event.
patchEntities() ¶ public
patchEntities(iterable<Cake\Datasource\EntityInterface> $entities, array $data, array<string, mixed> $options = []): array<TEntity|TPatchedEntity>
{@inheritDoc}
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 marshaled 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.
Templates
TPatchedEntity
of \Cake\Datasource\EntityInterface Parameters
-
iterable<Cake\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.
Returns
array<TEntity|TPatchedEntity>patchEntity() ¶ public
patchEntity(Cake\Datasource\EntityInterface $entity, array $data, array<string, mixed> $options = []): TPatchedEntity
{@inheritDoc}
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' => ['patchableFields' => ['*' => true]]
]
]);
$article = $this->Articles->patchEntity($article, $this->request->getData(), [
'associated' => ['Tags' => ['_joinData' => ['Users']]]
]);
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.
Templates
TPatchedEntity
of \Cake\Datasource\EntityInterface Parameters
-
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.
Returns
TPatchedEntitySee Also
processDelete() ¶ protected
processDelete(Cake\Datasource\EntityInterface $entity, ArrayObject<string, mixed> $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.
Parameters
-
Cake\Datasource\EntityInterface$entity The entity to delete.
-
ArrayObject<string, mixed>$options The options for the delete.
Returns
boolsuccess
Throws
InvalidArgumentExceptionif there are no primary key values of the passed entity
processFindOrCreate() ¶ protected
processFindOrCreate(Cake\ORM\Query\SelectQuery<TEntity|array>|callable|array $search, callable|array|null $callback = null, array<string, mixed> $options = []): TEntity|array
Performs the actual find and/or create of an entity based on the passed options.
Parameters
-
Cake\ORM\Query\SelectQuery<TEntity|array>|callable|array$search The criteria to find an existing record by, or a callable that will customize the find query.
-
callable|array|null$callback optional Data or 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.
Returns
TEntity|arrayAn entity.
Throws
Cake\ORM\Exception\PersistenceFailedExceptionWhen the entity couldn't be saved
InvalidArgumentExceptionprocessSave() ¶ protected
processSave(Cake\Datasource\EntityInterface $entity, ArrayObject<string, mixed> $options): Cake\Datasource\EntityInterface|false
Performs the actual saving of an entity based on the passed options.
Parameters
-
Cake\Datasource\EntityInterface$entity the entity to be saved
-
ArrayObject<string, mixed>$options the options to use for the save operation
Returns
Cake\Datasource\EntityInterface|falseThrows
Cake\Database\Exception\DatabaseExceptionWhen an entity is missing some of the primary keys.
Cake\ORM\Exception\RolledbackTransactionExceptionIf the transaction is aborted in the afterSave event.
query() ¶ public
query(): Cake\ORM\Query\SelectQuery<TEntity>
Creates a new SelectQuery instance for a table.
Returns
Cake\ORM\Query\SelectQuery<TEntity>removeBehavior() ¶ public
removeBehavior(string $name): $this
Removes a behavior from this table's behavior registry.
Example:
Remove a behavior from this table.
$this->removeBehavior('Tree');
Parameters
-
string$name The alias that the behavior was added with.
Returns
$thisSee Also
resolveRuleProvider() ¶ public
resolveRuleProvider(string $method): array{0: object, 1: string}|null
Get the object and method that should be used to invoke a validation rule method.
Resolves rule methods provided by behaviors, when the behavior's
implementedMethods config is set. The rule method name is matched
against the configured alias keys, case-insensitively.
Parameters
-
string$method The name of the rule method.
Returns
array{0: object, 1: string}|nullProvider and method to invoke, or null to invoke the method on the table itself.
rulesChecker() ¶ public
rulesChecker(): 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.
Returns
Cake\Datasource\RulesCheckerSee Also
save() ¶ public
save(Cake\Datasource\EntityInterface $entity, array<string, mixed> $options = []): TSavedEntity|false
{@inheritDoc}
Options
The options array accepts the following keys:
- atomic: Whether to execute the save and callbacks inside a database transaction (default: true)
- checkRules: Whether to check the rules on entity before saving, if the checking fails, it will abort the save operation. (default:true)
- associated: If
trueit will save 1st level associated entities as they are found in the passed$entitywhenever 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. Iffalseno associated records will be saved. (default:true) - checkExisting: Whether 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
checkRuleskey 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
resultproperty 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 committed 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' => [
'Addresses',
'checkRules' => false
]
]
]);
// Save no associations
$articles->save($entity, ['associated' => false]);
Templates
TSavedEntity
of \Cake\Datasource\EntityInterface Parameters
-
Cake\Datasource\EntityInterface$entity the entity to be saved
-
array<string, mixed>$options optional The options to use when saving.
Returns
TSavedEntity|falseReturns the entity on success. Returns false when the entity has errors, validation fails, rules checking fails, or the save operation fails. If the entity is not new and has no dirty fields, the entity is returned without performing any database operation.
Throws
Cake\ORM\Exception\RolledbackTransactionExceptionIf the transaction is aborted in the afterSave event.
saveMany() ¶ public
saveMany(iterable<TSavedEntity> $entities, array<string, mixed> $options = []): ($entities is array ? array<TSavedEntity> : iterable<TSavedEntity>)|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.
Templates
TSavedEntity
of \Cake\Datasource\EntityInterface Parameters
-
iterable<TSavedEntity>$entities Entities to save.
-
array<string, mixed>$options optional Options used when calling Table::save() for each entity.
Returns
($entities is array ? array<TSavedEntity> : iterable<TSavedEntity>)|falseFalse on failure, entities list on success.
Throws
ExceptionsaveManyOrFail() ¶ public
saveManyOrFail(iterable<TSavedEntity> $entities, array<string, mixed> $options = []): $entities is array ? array<TSavedEntity> : iterable<TSavedEntity>
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.
Templates
TSavedEntity
of \Cake\Datasource\EntityInterface Parameters
-
iterable<TSavedEntity>$entities Entities to save.
-
array<string, mixed>$options optional Options used when calling Table::save() for each entity.
Returns
$entities is array ? array<TSavedEntity> : iterable<TSavedEntity>Entities list.
Throws
ExceptionCake\ORM\Exception\PersistenceFailedExceptionIf an entity couldn't be saved.
saveOrFail() ¶ public
saveOrFail(TSavedEntity $entity, array<string, mixed> $options = []): TSavedEntity
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.
Templates
TSavedEntity
of \Cake\Datasource\EntityInterface Parameters
-
TSavedEntity$entity the entity to be saved
-
array<string, mixed>$options optional The options to use when saving.
Returns
TSavedEntityThrows
Cake\ORM\Exception\PersistenceFailedExceptionWhen the entity couldn't be saved
See Also
selectQuery() ¶ public
selectQuery(): Cake\ORM\Query\SelectQuery<TEntity>
Creates a new select query
Returns
Cake\ORM\Query\SelectQuery<TEntity>setAlias() ¶ public
setAlias(string $alias): $this
Sets the table alias.
Parameters
-
string$alias Table alias
Returns
$thissetConnection() ¶ public
setConnection(Cake\Database\Connection $connection): $this
Sets the connection instance.
Parameters
-
Cake\Database\Connection$connection The connection instance
Returns
$thissetDisplayField() ¶ public
setDisplayField(array<string>|string $field): $this
Sets the display field.
Parameters
-
array<string>|string$field Name to be used as display field.
Returns
$thissetEntityClass() ¶ public
setEntityClass(string $name): $this
Sets the class used to hydrate rows for this table.
Parameters
-
string$name The name of the class to use
Returns
$thisThrows
Cake\ORM\Exception\MissingEntityExceptionwhen the entity class cannot be found
setEventManager() ¶ public
setEventManager(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.
Parameters
-
Cake\Event\EventManagerInterface$eventManager the eventManager to set
Returns
$thissetFieldMatchers() ¶ protected
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.
Parameters
-
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
Returns
array<string, mixed>setPrimaryKey() ¶ public
setPrimaryKey(array<string>|string $key): $this
Sets the primary key field name.
Parameters
-
array<string>|string$key Sets a new name to be used as primary key
Returns
$thissetRegistryAlias() ¶ public
setRegistryAlias(string $registryAlias): $this
Sets the table registry key used to create this table instance.
Parameters
-
string$registryAlias The key used to access this object.
Returns
$thissetSchema() ¶ public
setSchema(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.
Parameters
-
Cake\Database\Schema\TableSchemaInterface|array$schema Schema to be used for this table
Returns
$thissetTable() ¶ public
setTable(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.
Parameters
-
string$table Table name.
Returns
$thissetValidator() ¶ public
setValidator(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);
Parameters
-
string$name The name of a validator to be set.
-
Cake\Validation\Validator$validator Validator object to be set.
Returns
$thissubquery() ¶ public
subquery(): Cake\ORM\Query\SelectQuery<TEntity|array>
Creates a new Query instance with field auto aliasing disabled.
This is useful for subqueries.
Returns
Cake\ORM\Query\SelectQuery<TEntity|array>transactionCommitted() ¶ protected
transactionCommitted(bool $atomic, bool $primary): bool
Checks if the caller would have executed a commit on a transaction.
Parameters
-
bool$atomic True if an atomic transaction was used.
-
bool$primary True if a primary was used.
Returns
boolReturns true if a transaction was committed.
unhydratedFind() ¶ public
unhydratedFind(string $type = 'all', mixed ...$args): Cake\ORM\Query\UnhydratedSelectQuery
Type-safe non-hydrated read. Equivalent in behavior to
find($type, ...)->disableHydration() but the type system knows the
results are arrays rather than entities.
Construction methods (where/join/order/contain/finders) behave the same as on a regular {@see SelectQuery}; only the result-fetch methods (first/firstOrFail/all/toArray/iteration) differ in shape.
$rows = $articlesTable->unhydratedFind()->where(['published' => true])->all();
// $rows: iterable<array<string, mixed>>
Only finders that mutate and return the query they were given are
supported here (the overwhelming majority). A finder that discards the
passed query and returns a freshly built one (e.g. by delegating to
find()) cannot preserve the non-hydrating contract and triggers an
exception rather than a silent hydrated result.
Parameters
-
string$type optional The type of finder to call.
-
mixed...$args Arguments matching the finder's parameters.
Returns
Cake\ORM\Query\UnhydratedSelectQueryThrows
Cake\Core\Exception\CakeExceptionWhen the finder does not return the passed query.
unhydratedSelectQuery() ¶ public
unhydratedSelectQuery(): Cake\ORM\Query\UnhydratedSelectQuery
Creates a new non-hydrating select query.
Returns
Cake\ORM\Query\UnhydratedSelectQueryupdate() ¶ protected
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
Parameters
-
Cake\Datasource\EntityInterface$entity the subject entity from were $data was extracted
-
array$data The actual data that needs to be saved
Returns
Cake\Datasource\EntityInterface|falseThrows
InvalidArgumentExceptionWhen primary key data is missing.
updateAll() ¶ public
updateAll(Cake\Database\Expression\QueryExpression|Closure|array|string $fields, Cake\Database\ExpressionInterface|Closure|array|string|null $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.
Parameters
-
Cake\Database\Expression\QueryExpression|Closure|array|string$fields A hash of field => new value.
-
Cake\Database\ExpressionInterface|Closure|array|string|null$conditions Conditions to be used, accepts anything Query::where()
Returns
intCount Returns the affected rows.
updateQuery() ¶ public
updateQuery(): Cake\ORM\Query\UpdateQuery
Creates a new update query
Returns
Cake\ORM\Query\UpdateQueryvalidateUnique() ¶ public
validateUnique(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.
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.
Parameters
-
mixed$value The value of column to be checked for uniqueness.
-
array<string, mixed>$options optional 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.
Returns
boolTrue if the value is unique, or false if a non-scalar, non-unique value was given.
validationDefault() ¶ public
validationDefault(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.
Parameters
-
Cake\Validation\Validator$validator The validator that can be modified to add some rules to it.
Returns
Cake\Validation\ValidatorvalidationMethodExists() ¶ protected
validationMethodExists(string $name): bool
Checks if validation method exists.
Parameters
-
string$name
Returns
boolProperty Detail
$alias ¶ protected
Human name giving to this particular instance. Multiple objects representing the same database table can exist by using different aliases.
Type
string|null$assertEntityClass ¶ protected
Whether to assert that entities passed to save/delete/patch/loadInto match the table's configured entity class. Disable per table via {@see Table::disableEntityClassAssertion()} when foreign entities are passed intentionally.
Type
bool$associations ¶ protected
The associations container for this Table.
Type
Cake\ORM\AssociationCollection$displayField ¶ protected
The name of the field that represents a human-readable representation of a row
Type
array<string>|string|null$entityClass ¶ protected
The name of the class that represent a single row for this table
Type
class-string<TEntity>|null$eventManager ¶ protected
Instance of the Cake\Event\EventManager this object is using to dispatch inner events.
Type
Cake\Event\EventManagerInterface$primaryKey ¶ protected
The name of the field that represents the primary key in the table
Type
array<string>|string|null$rulesChecker ¶ protected
The domain rules to be applied to entities saved by this table
Type
Cake\Datasource\RulesChecker|null$schema ¶ protected
The schema object containing a description of this table fields
Type
Cake\Database\Schema\TableSchemaInterface|null$validators ¶ protected
A list of validation objects indexed by name
Type
array<Cake\Validation\Validator>