CoursesTable
extends Table
in package
uses
MergeDeleteTrait, ApplySettingsTrait, CheckAddTrait, ToggleTrait
Courses Model
Used for testing the traits and behaviors.
Tags
Table of Contents
Constants
- BUILD_VALIDATOR_EVENT = 'Model.buildValidator'
- The name of the event dispatched when a validator has been built.
- DEFAULT_VALIDATOR = 'default'
- Name of default validation set.
- IS_UNIQUE_CLASS = \Cake\ORM\Rule\IsUnique::class
- The IsUnique class name that is used.
- RULES_CLASS = \Cake\ORM\RulesChecker::class
- The rules class name that is used.
- VALIDATOR_PROVIDER_NAME = 'table'
- The alias this object is assigned to validators as.
Properties
- $applyError : string
- $cacheReadCnt : int
- track successful cache read counts.
- $checkAdd_new_cnt : int
- Track the new count for each query
- $checkAdd_update_cnt : int
- Track the updated count for each query
- $checkAddIds : array<string, array<string|int, mixed>>
- Keeps track of the ids that have been created/checked previously.
- $CoursesStudents : CoursesStudentsTable
- $dbReadCnt : int
- track successful database read counts.
- $dbWriteCnt : int
- track successful database write counts.
- $Students : StudentsTable
- $TeachersPet : StudentsTable
- $useCaching : bool
- If we should use memory caching, always reach out to the database.
- $_alias : string|null
- Human name giving to this particular instance. Multiple objects representing the same database table can exist by using different aliases.
- $_associations : AssociationCollection
- The associations container for this Table.
- $_behaviors : BehaviorRegistry
- BehaviorRegistry for this table
- $_connection : Connection|null
- Connection instance
- $_displayField : array<string|int, string>|string|null
- The name of the field that represents a human-readable representation of a row
- $_entityClass : string
- The name of the class that represent a single row for this table
- $_eventClass : string
- Default class name for new event objects.
- $_eventManager : EventManagerInterface|null
- Instance of the Cake\Event\EventManager this object is using to dispatch inner events.
- $_primaryKey : array<string|int, string>|string|null
- The name of the field that represents the primary key in the table
- $_registryAlias : string|null
- Registry key used to create this table object
- $_rulesChecker : RulesChecker
- The domain rules to be applied to entities saved by this table
- $_schema : TableSchemaInterface|null
- The schema object containing a description of this table fields
- $_table : string|null
- Name of the table as it can be found in the database
- $_validatorClass : string
- Validator class.
- $_validators : array<string|int, Validator>
- A list of validation objects indexed by name
- $checkAddName : string
- The default field name for the name field
- $checkAddSlug : string
- The default field name for the slug field
- $lastEntity : Entity|null
- Hold the last record checked/created
Methods
- __call() : mixed
- Handles behavior delegation + dynamic finders.
- __construct() : mixed
- Initializes a new instance
- __debugInfo() : array<string, mixed>
- Returns an array that can be used to describe the internal state of this object.
- __get() : Association
- Returns the association named after the passed value if exists, otherwise throws an exception.
- __isset() : bool
- Returns whether an association named after the passed value exists for this table.
- addAssociations() : $this
- Setup multiple associations.
- addBehavior() : $this
- Add a behavior.
- addBehaviors() : $this
- Adds an array of behaviors to the table's behavior collection.
- aliasField() : string
- Alias a field with the table's current alias.
- applySettings() : null|int
- Allows changing of multiple fields in batch by their unique ids.
- associations() : AssociationCollection
- Get the associations collection for this table.
- behaviors() : BehaviorRegistry
- Returns the behavior registry for this table.
- belongsTo() : BelongsTo
- Creates a new BelongsTo association between this table and a target table. A "belongs to" association is a N-1 relationship where this table is the N side, and where there is a single associated record in the target table for each one in this table.
- belongsToMany() : BelongsToMany
- Creates a new BelongsToMany association between this table and a target table. A "belongs to many" association is a M-N relationship.
- buildRules() : RulesChecker
- {@inheritDoc}
- callFinder() : Query
- Calls a finder method and applies it to the passed query.
- checkAdd() : EntityInterface|int
- Checks if a record exist by it's slug, if not, it creates the record
- checkAdd() : Course
- checkRules() : bool
- Returns whether the passed entity complies with all the rules stored in the rules checker.
- defaultConnectionName() : string
- Get the default connection name.
- delete() : bool
- Delete a single entity.
- deleteAll() : int
- Deletes all records matching the provided conditions.
- deleteMany() : iterable<string|int, EntityInterface>|false
- Deletes multiple entities of a table.
- deleteManyOrFail() : iterable<string|int, EntityInterface>
- Deletes multiple entities of a table.
- deleteOrFail() : true
- Try to delete an entity or throw a PersistenceFailedException if the entity is new, has no primary key value, application rules checks failed or the delete was aborted by a callback.
- dispatchEvent() : EventInterface
- Wrapper for creating and dispatching events.
- exists() : bool
- Returns true if there is any record in this repository matching the specified conditions.
- find() : Query
- Creates a new Query for this repository and applies some defaults based on the type of search that was selected.
- findAll() : Query
- Returns the query as passed.
- findAvailable() : Query<string|int, mixed>
- Finder methond to get all available Courses.
- findList() : Query
- Sets up a query object so results appear as an indexed array, useful for any place where you would want a list such as for populating input select boxes.
- findMergeRecords() : Query<string|int, mixed>
- Gets the list of available records for determining which record to merge to.
- findOrCreate() : EntityInterface
- Finds an existing record or creates a new one.
- findThreaded() : Query
- Results for this finder will be a nested array, and is appropriate if you want to use the parent_id field of your model data to build nested results.
- fixName() : string
- Fixes the name if we need to.
- fixNameCommon() : string
- Common manipulation of an entity's name
- get() : EntityInterface
- Returns a single record after finding it by its primary key, if no record is found this method throws an exception.
- get() : Course
- Returns a single record after finding it by its primary key, if no record is found this method throws an exception.
- getAlias() : string
- Returns the table alias.
- getApplyError() : string
- Gets an error is one happened.
- getAssociation() : Association
- Returns an association object configured for the specified alias.
- getBehavior() : Behavior
- Get a behavior from the registry.
- getCheckAdd() : Entity|null
- Checks the checkadd cache and returns the id, or false
- getConnection() : Connection
- Returns the connection instance.
- getDisplayField() : array<string|int, string>|string|null
- Returns the display field.
- getEntityClass() : string
- Returns the class used to hydrate rows for this table.
- getEventManager() : EventManagerInterface
- Returns the Cake\Event\EventManager manager instance for this object.
- getLastEntity() : null|Entity
- Returns the last entity added to the cache
- getMergeStats() : array<string, array<string, string|int>>
- Get merge stats for a record to be deleted.
- getNameField() : string
- Gets the nameField()
- getPrimaryKey() : array<string|int, string>|string
- Returns the primary key field name.
- getRegistryAlias() : string
- Returns the table registry key used to create this table instance.
- getSaveOptionsBuilder() : SaveOptionsBuilder
- Gets a SaveOptionsBuilder instance.
- getSchema() : TableSchemaInterface
- Returns the schema table object describing this table's properties.
- getSlugField() : string
- Gets the slugField()
- getTable() : string
- Returns the database table name.
- getUseCache() : bool
- Gets if we're using memory caching.
- getValidator() : 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.
- hasAssociation() : bool
- Checks whether a specific association exists on this Table instance.
- hasBehavior() : bool
- Check if a behavior with the given alias has been loaded.
- hasField() : bool
- Test to see if a Table has a specific field/column.
- hasFinder() : bool
- Returns true if the finder exists for the table
- hasMany() : HasMany
- Creates a new HasMany association between this table and a target table. A "has many" association is a 1-N relationship.
- hasOne() : HasOne
- Creates a new HasOne association between this table and a target table. A "has one" association is a 1-1 relationship.
- hasValidator() : bool
- Checks whether a validator has been set.
- implementedEvents() : array<string, mixed>
- Get the Model callbacks this table is interested in.
- initCheckAdd() : void
- Initialize method
- initialize() : void
- Initialize method
- loadInto() : EntityInterface|array<string|int, EntityInterface>
- Loads the specified associations in the passed entity or list of entities by executing extra queries in the database and merging the results in the appropriate properties.
- marshaller() : Marshaller
- Get the object used to marshal/convert array data into objects.
- mergeDelete() : bool
- Allows to merge associated records from one attribute to another, then delete the old record.
- newEmptyEntity() : EntityInterface
- This creates a new entity object.
- newEntities() : array<string|int, EntityInterface>
- Create a list of entities + associated entities from an array.
- newEntity() : EntityInterface
- Create a new entity + associated entities from an array.
- newEntity() : Course
- Create a new entity + associated entities from an array.
- patchEntities() : array<string|int, EntityInterface>
- Merges each of the elements passed in `$data` into the entities found in `$entities` respecting the accessible fields configured on the entities.
- patchEntity() : EntityInterface
- Merges the passed `$data` into `$entity` respecting the accessible fields configured on the entity. Returns the same entity after being altered.
- query() : Query
- Creates a new Query instance for a table.
- removeBehavior() : $this
- Removes a behavior from this table's behavior registry.
- rulesChecker() : RulesChecker
- Returns the RulesChecker for this instance.
- save() : EntityInterface|false
- Persists an entity based on the fields that are marked as dirty and returns the same entity after a successful save or false in case of any error.
- saveMany() : iterable<string|int, EntityInterface>|false
- Persists multiple entities of a table.
- saveManyOrFail() : iterable<string|int, EntityInterface>
- Persists multiple entities of a table.
- saveOrFail() : EntityInterface
- Try to save an entity or throw a PersistenceFailedException if the application rules checks failed, the entity contains errors or the save was aborted by a callback.
- saveOrFail() : Course
- 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.
- setAlias() : $this
- Sets the table alias.
- setApplyError() : void
- Sets an error if one happens.
- setCheckAdd() : Entity
- Adds the id to the checkadd cache
- setConnection() : $this
- Sets the connection instance.
- setDisplayField() : $this
- Sets the display field.
- setEntityClass() : $this
- Sets the class used to hydrate rows for this table.
- setEventManager() : $this
- Returns the Cake\Event\EventManagerInterface instance for this object.
- setLastEntity() : void
- Sets tracking on the last entity that was added to the cache
- setNameField() : void
- Sets the name field, if different from the default
- setPrimaryKey() : $this
- Sets the primary key field name.
- setRegistryAlias() : $this
- Sets the table registry key used to create this table instance.
- setSchema() : $this
- Sets the schema table object describing this table's properties.
- setSlugField() : void
- Sets the slug field, if different from the default
- setTable() : $this
- Sets the database table name.
- setUseCache() : void
- Sets if we're using memory caching.
- setValidator() : $this
- This method stores a custom validator under the given name.
- slugify() : string
- Creates a slug from the input
- subquery() : Query
- Creates a new Query::subquery() instance for a table.
- toggle() : bool
- Allows toggling of boolean fields.
- updateAll() : int
- Update all matching records.
- validateUnique() : bool
- Validator method used to check the uniqueness of a value for a column.
- validationDefault() : Validator
- Returns the default validator object. Subclasses can override this function to add a default validation set to the validator object.
- _deleteMany() : EntityInterface|null
- _dynamicFinder() : Query
- Provides the dynamic findBy and findAllBy methods.
- _executeTransaction() : mixed
- Handles the logic executing of a worker inside a transaction.
- _getFindOrCreateQuery() : Query
- Gets the query object for findOrCreate().
- _initializeSchema() : TableSchemaInterface
- Override this function in order to alter the schema used by this table.
- _insert() : EntityInterface|false
- Auxiliary function to handle the insert of an entity's data in the table
- _newId() : string|null
- Generate a primary key value for a new record.
- _onSaveSuccess() : bool
- Handles the saving of children associations and executing the afterSave logic once the entity for this table has been saved successfully.
- _processDelete() : bool
- Perform the delete operation.
- _processFindOrCreate() : EntityInterface|array<string|int, mixed>
- Performs the actual find and/or create of an entity based on the passed options.
- _processSave() : EntityInterface|false
- Performs the actual saving of an entity based on the passed options.
- _saveMany() : iterable<string|int, EntityInterface>
- _setFieldMatchers() : 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.
- _transactionCommitted() : bool
- Checks if the caller would have executed a commit on a transaction.
- _update() : EntityInterface|false
- Auxiliary function to handle the update of an entity's data in the table
- checkAliasLengths() : void
- Checks if all table name + column name combinations used for queries fit into the max length allowed by database driver.
- createValidator() : Validator
- Creates a validator using a custom method inside your class.
- findAssociation() : Association|null
- Returns an association object configured for the specified alias if any.
- validationMethodExists() : bool
Constants
BUILD_VALIDATOR_EVENT
The name of the event dispatched when a validator has been built.
public
string
BUILD_VALIDATOR_EVENT
= 'Model.buildValidator'
DEFAULT_VALIDATOR
Name of default validation set.
public
string
DEFAULT_VALIDATOR
= 'default'
IS_UNIQUE_CLASS
The IsUnique class name that is used.
public
string
IS_UNIQUE_CLASS
= \Cake\ORM\Rule\IsUnique::class
RULES_CLASS
The rules class name that is used.
public
string
RULES_CLASS
= \Cake\ORM\RulesChecker::class
VALIDATOR_PROVIDER_NAME
The alias this object is assigned to validators as.
public
string
VALIDATOR_PROVIDER_NAME
= 'table'
Properties
$applyError
public
string
$applyError
= ''
The error if one happens.
$cacheReadCnt
track successful cache read counts.
public
int
$cacheReadCnt
= 0
$checkAdd_new_cnt
Track the new count for each query
public
int
$checkAdd_new_cnt
= 0
$checkAdd_update_cnt
Track the updated count for each query
public
int
$checkAdd_update_cnt
= 0
$checkAddIds
Keeps track of the ids that have been created/checked previously.
public
array<string, array<string|int, mixed>>
$checkAddIds
= []
$CoursesStudents
public
CoursesStudentsTable
$CoursesStudents
$dbReadCnt
track successful database read counts.
public
int
$dbReadCnt
= 0
$dbWriteCnt
track successful database write counts.
public
int
$dbWriteCnt
= 0
$Students
public
StudentsTable
$Students
$TeachersPet
public
StudentsTable
$TeachersPet
$useCaching
If we should use memory caching, always reach out to the database.
public
bool
$useCaching
= true
In benchmarking, it seems faster right now to disable memory caching.
$_alias
Human name giving to this particular instance. Multiple objects representing the same database table can exist by using different aliases.
protected
string|null
$_alias
$_associations
The associations container for this Table.
protected
AssociationCollection
$_associations
$_behaviors
BehaviorRegistry for this table
protected
BehaviorRegistry
$_behaviors
$_connection
Connection instance
protected
Connection|null
$_connection
$_displayField
The name of the field that represents a human-readable representation of a row
protected
array<string|int, string>|string|null
$_displayField
$_entityClass
The name of the class that represent a single row for this table
protected
string
$_entityClass
Tags
$_eventClass
Default class name for new event objects.
protected
string
$_eventClass
= \Cake\Event\Event::class
$_eventManager
Instance of the Cake\Event\EventManager this object is using to dispatch inner events.
protected
EventManagerInterface|null
$_eventManager
$_primaryKey
The name of the field that represents the primary key in the table
protected
array<string|int, string>|string|null
$_primaryKey
$_registryAlias
Registry key used to create this table object
protected
string|null
$_registryAlias
$_rulesChecker
The domain rules to be applied to entities saved by this table
protected
RulesChecker
$_rulesChecker
$_schema
The schema object containing a description of this table fields
protected
TableSchemaInterface|null
$_schema
$_table
Name of the table as it can be found in the database
protected
string|null
$_table
$_validatorClass
Validator class.
protected
string
$_validatorClass
= \Cake\Validation\Validator::class
$_validators
A list of validation objects indexed by name
protected
array<string|int, Validator>
$_validators
= []
$checkAddName
The default field name for the name field
protected
string
$checkAddName
= 'name'
$checkAddSlug
The default field name for the slug field
protected
string
$checkAddSlug
= 'slug'
$lastEntity
Hold the last record checked/created
protected
Entity|null
$lastEntity
= null
Methods
__call()
Handles behavior delegation + dynamic finders.
public
__call(string $method, array<string|int, mixed> $args) : mixed
If your Table uses any behaviors you can call them as if they were on the table object.
Parameters
- $method : string
-
name of the method to be invoked
- $args : array<string|int, mixed>
-
List of arguments passed to the function
Tags
__construct()
Initializes a new instance
public
__construct([array<string, mixed> $config = [] ]) : mixed
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
- $config : array<string, mixed> = []
-
List of options for this table
__debugInfo()
Returns an array that can be used to describe the internal state of this object.
public
__debugInfo() : array<string, mixed>
Return values
array<string, mixed>__get()
Returns the association named after the passed value if exists, otherwise throws an exception.
public
__get(string $property) : Association
Parameters
- $property : string
-
the association name
Tags
Return values
Association__isset()
Returns whether an association named after the passed value exists for this table.
public
__isset(string $property) : bool
Parameters
- $property : string
-
the association name
Return values
booladdAssociations()
Setup multiple associations.
public
addAssociations(array<string|int, mixed> $params) : $this
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
- $params : array<string|int, mixed>
-
Set of associations to bind (indexed by association type)
Tags
Return values
$thisaddBehavior()
Add a behavior.
public
addBehavior(string $name[, array<string, mixed> $options = [] ]) : $this
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
- $name : string
-
The name of the behavior. Can be a short class reference.
- $options : array<string, mixed> = []
-
The options for the behavior to use.
Tags
Return values
$thisaddBehaviors()
Adds an array of behaviors to the table's behavior collection.
public
addBehaviors(array<string|int, mixed> $behaviors) : $this
Example:
$this->addBehaviors([
'Timestamp',
'Tree' => ['level' => 'level'],
]);
Parameters
- $behaviors : array<string|int, mixed>
-
All the behaviors to load.
Tags
Return values
$thisaliasField()
Alias a field with the table's current alias.
public
aliasField(string $field) : string
If field is already aliased it will result in no-op.
Parameters
- $field : string
-
The field to alias.
Return values
string —The field prefixed with the table alias.
applySettings()
Allows changing of multiple fields in batch by their unique ids.
public
applySettings([array<string, mixed> $data = [] ][, array<int, int> $ids = [] ][, null|Entity $entity = null ][, null|string $record_field = null ]) : null|int
Parameters
- $data : array<string, mixed> = []
-
The data from the form with the apply key set in it.
- $ids : array<int, int> = []
-
The unique ids that will have these changes applied.
- $entity : null|Entity = null
-
The entity to attach to records
- $record_field : null|string = null
-
The field on the records that the entity should be attached to.
Tags
Return values
null|int —If the save was successfull, return the record count.
associations()
Get the associations collection for this table.
public
associations() : AssociationCollection
Return values
AssociationCollection —The collection of association objects.
behaviors()
Returns the behavior registry for this table.
public
behaviors() : BehaviorRegistry
Return values
BehaviorRegistry —The BehaviorRegistry instance.
belongsTo()
Creates a new BelongsTo association between this table and a target table. A "belongs to" association is a N-1 relationship where this table is the N side, and where there is a single associated record in the target table for each one in this table.
public
belongsTo(string $associated[, array<string, mixed> $options = [] ]) : BelongsTo
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
- $associated : string
-
the alias for the target table. This is used to uniquely identify the association
- $options : array<string, mixed> = []
-
list of options to configure the association definition
Return values
BelongsTobelongsToMany()
Creates a new BelongsToMany association between this table and a target table. A "belongs to many" association is a M-N relationship.
public
belongsToMany(string $associated[, array<string, mixed> $options = [] ]) : BelongsToMany
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
- $associated : string
-
the alias for the target table. This is used to uniquely identify the association
- $options : array<string, mixed> = []
-
list of options to configure the association definition
Return values
BelongsToManybuildRules()
{@inheritDoc}
public
buildRules(RulesChecker $rules) : RulesChecker
Parameters
- $rules : RulesChecker
-
The rules object to be modified.
Return values
RulesCheckercallFinder()
Calls a finder method and applies it to the passed query.
public
callFinder(string $type, Query $query[, array<string, mixed> $options = [] ]) : Query
Parameters
- $type : string
-
Name of the finder to be called.
- $query : Query
-
The query object to apply the finder options to.
- $options : array<string, mixed> = []
-
List of options to pass to the finder.
Tags
Return values
QuerycheckAdd()
Checks if a record exist by it's slug, if not, it creates the record
public
checkAdd([mixed $name = null ][, null|string $slug = null ][, array<string, mixed> $fields = [] ][, bool|array<string|int, mixed> $returnEntity = false ]) : EntityInterface|int
Parameters
- $name : mixed = null
-
The name of the record
- $slug : null|string = null
-
The unique slug to look for
- $fields : array<string, mixed> = []
-
The list of other details to include in the new record
- $returnEntity : bool|array<string|int, mixed> = false
-
If true, return the entity, otherwise return the entity id. If it's an array, treat it as options
Tags
Return values
EntityInterface|int —Either the existing entity, or the newly created entity's id.
checkAdd()
public
checkAdd([mixed $name = ][, string $slug = null ][, array<string|int, mixed> $fields = [] ][, bool|array<string|int, mixed> $returnEntity = false ]) : Course
Parameters
- $name : mixed =
- $slug : string = null
- $fields : array<string|int, mixed> = []
- $returnEntity : bool|array<string|int, mixed> = false
Return values
CoursecheckRules()
Returns whether the passed entity complies with all the rules stored in the rules checker.
public
checkRules(EntityInterface $entity[, string $operation = RulesChecker::CREATE ][, ArrayObject|array<string|int, mixed>|null $options = null ]) : bool
Parameters
- $entity : EntityInterface
-
The entity to check for validity.
- $operation : string = RulesChecker::CREATE
-
The operation being run. Either 'create', 'update' or 'delete'.
- $options : ArrayObject|array<string|int, mixed>|null = null
-
The options To be passed to the rules.
Return values
booldefaultConnectionName()
Get the default connection name.
public
static defaultConnectionName() : string
This method is used to get the fallback connection name if an instance is created through the TableLocator without a connection.
Tags
Return values
stringdelete()
Delete a single entity.
public
delete(EntityInterface $entity[, ArrayAccess|array<string|int, mixed> $options = [] ]) : bool
For HasMany and HasOne associations records will be removed based on
the dependent option. Join table records in BelongsToMany associations
will always be removed. You can use the cascadeCallbacks
option
when defining associations to change how associated data is deleted.
Options
-
atomic
Defaults to true. When true the deletion happens within a transaction. -
checkRules
Defaults to true. Check deletion rules before deleting the record.
Events
-
Model.beforeDelete
Fired before the delete occurs. If stopped the delete will be aborted. Receives the event, entity, and options. -
Model.afterDelete
Fired after the delete has been successful. Receives the event, entity, and options. -
Model.afterDeleteCommit
Fired after the transaction is committed for an atomic delete. Receives the event, entity, and options.
The options argument will be converted into an \ArrayObject instance for the duration of the callbacks, this allows listeners to modify the options used in the delete operation.
Parameters
- $entity : EntityInterface
-
The entity to remove.
- $options : ArrayAccess|array<string|int, mixed> = []
-
The options for the delete.
Return values
bool —success
deleteAll()
Deletes all records matching the provided conditions.
public
deleteAll(mixed $conditions) : int
Parameters
- $conditions : mixed
-
Conditions to be used, accepts anything Query::where() can take.
Tags
Return values
int —Returns the number of affected rows.
deleteMany()
Deletes multiple entities of a table.
public
deleteMany(iterable<string|int, EntityInterface> $entities[, ArrayAccess|array<string|int, mixed> $options = [] ]) : iterable<string|int, EntityInterface>|false
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
- $entities : iterable<string|int, EntityInterface>
-
Entities to delete.
- $options : ArrayAccess|array<string|int, mixed> = []
-
Options used when calling Table::save() for each entity.
Tags
Return values
iterable<string|int, EntityInterface>|false —Entities list on success, false on failure.
deleteManyOrFail()
Deletes multiple entities of a table.
public
deleteManyOrFail(iterable<string|int, EntityInterface> $entities[, ArrayAccess|array<string|int, mixed> $options = [] ]) : iterable<string|int, EntityInterface>
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
- $entities : iterable<string|int, EntityInterface>
-
Entities to delete.
- $options : ArrayAccess|array<string|int, mixed> = []
-
Options used when calling Table::save() for each entity.
Tags
Return values
iterable<string|int, EntityInterface> —Entities list.
deleteOrFail()
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.
public
deleteOrFail(EntityInterface $entity[, ArrayAccess|array<string|int, mixed> $options = [] ]) : true
Parameters
- $entity : EntityInterface
-
The entity to remove.
- $options : ArrayAccess|array<string|int, mixed> = []
-
The options for the delete.
Tags
Return values
truedispatchEvent()
Wrapper for creating and dispatching events.
public
dispatchEvent(string $name[, array<string|int, mixed>|null $data = null ][, object|null $subject = null ]) : EventInterface
Returns a dispatched event.
Parameters
- $name : string
-
Name of the event.
- $data : array<string|int, mixed>|null = null
-
Any value you wish to be transported with this event to it can be read by listeners.
- $subject : object|null = null
-
The object that this event applies to ($this by default).
Return values
EventInterfaceexists()
Returns true if there is any record in this repository matching the specified conditions.
public
exists(mixed $conditions) : bool
Parameters
- $conditions : mixed
-
list of conditions to pass to the query
Tags
Return values
boolfind()
Creates a new Query for this repository and applies some defaults based on the type of search that was selected.
public
find([string $type = 'all' ][, array<string, mixed> $options = [] ]) : Query
Model.beforeFind event
Each find() will trigger a Model.beforeFind
event for all attached
listeners. Any listener can set a valid result set using $query
By default, $options
will recognize the following keys:
- fields
- conditions
- order
- limit
- offset
- page
- group
- having
- contain
- join
Usage
Using the options array:
$query = $articles->find('all', [
'conditions' => ['published' => 1],
'limit' => 10,
'contain' => ['Users', 'Comments']
]);
Using the builder interface:
$query = $articles->find()
->where(['published' => 1])
->limit(10)
->contain(['Users', 'Comments']);
Calling finders
The find() method is the entry point for custom finder methods. You can invoke a finder by specifying the type:
$query = $articles->find('published');
Would invoke the findPublished
method.
Parameters
- $type : string = 'all'
-
the type of query to perform
- $options : array<string, mixed> = []
-
An array that will be passed to Query::applyOptions()
Return values
Query —The query builder
findAll()
Returns the query as passed.
public
findAll(Query $query, array<string, mixed> $options) : Query
By default findAll() applies no conditions, you
can override this method in subclasses to modify how find('all')
works.
Parameters
- $query : Query
-
The query to find with
- $options : array<string, mixed>
-
The options to use for the find
Return values
Query —The query builder
findAvailable()
Finder methond to get all available Courses.
public
findAvailable(Query<string|int, mixed> $query[, array<string|int, mixed> $options = [] ]) : Query<string|int, mixed>
Parameters
- $query : Query<string|int, mixed>
-
The query object to modify.
- $options : array<string|int, mixed> = []
-
The options either specific to this finder, or to pass through.
Return values
Query<string|int, mixed> —Return the modified query object.
findList()
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.
public
findList(Query $query, array<string, mixed> $options) : Query
When calling this finder, the fields passed are used to determine what should be used as the array key, value and optionally what to group the results by. By default, the primary key for the model is used for the key, and the display field as value.
The results of this finder will be in the following form:
[
1 => 'value for id 1',
2 => 'value for id 2',
4 => 'value for id 4'
]
You can specify which property will be used as the key and which as value
by using the $options
array, when not specified, it will use the results
of calling primaryKey
and displayField
respectively in this table:
$table->find('list', [
'keyField' => 'name',
'valueField' => 'age'
]);
The valueField
can also be an array, in which case you can also specify
the valueSeparator
option to control how the values will be concatenated:
$table->find('list', [
'valueField' => ['first_name', 'last_name'],
'valueSeparator' => ' | ',
]);
The results of this finder will be in the following form:
[
1 => 'John | Doe',
2 => 'Steve | Smith'
]
Results can be put together in bigger groups when they share a property, you
can customize the property to use for grouping by setting groupField
:
$table->find('list', [
'groupField' => 'category_id',
]);
When using a groupField
results will be returned in this format:
[
'group_1' => [
1 => 'value for id 1',
2 => 'value for id 2',
]
'group_2' => [
4 => 'value for id 4'
]
]
Parameters
- $query : Query
-
The query to find with
- $options : array<string, mixed>
-
The options for the find
Return values
Query —The query builder
findMergeRecords()
Gets the list of available records for determining which record to merge to.
public
findMergeRecords(Query<string|int, mixed> $query[, array<string|int, mixed> $options = [] ]) : Query<string|int, mixed>
This is a custom finder.
Parameters
- $query : Query<string|int, mixed>
-
The query object to modify.
- $options : array<string|int, mixed> = []
-
The options either specific to this finder, or to pass through. There should be an 'sourceId' option to exclude.
Return values
Query<string|int, mixed> —Return the modified query object.
findOrCreate()
Finds an existing record or creates a new one.
public
findOrCreate(Query|callable|array<string|int, mixed> $search[, callable|null $callback = null ][, array<string, mixed> $options = [] ]) : EntityInterface
A find() will be done to locate an existing record using the attributes defined in $search. If records matches the conditions, the first record will be returned.
If no record can be found, a new entity will be created with the $search properties. If a callback is provided, it will be called allowing you to define additional default values. The new entity will be saved and returned.
If your find conditions require custom order, associations or conditions, then the $search parameter can be a callable that takes the Query as the argument, or a \Cake\ORM\Query object passed as the $search parameter. Allowing you to customize the find results.
Options
The options array is passed to the save method with exception to the following keys:
- atomic: Whether to execute the methods for find, save and callbacks inside a database transaction (default: true)
- defaults: Whether to use the search criteria as default values for the new entity (default: true)
Parameters
- $search : Query|callable|array<string|int, mixed>
-
The criteria to find existing records by. Note that when you pass a query object you'll have to use the 2nd arg of the method to modify the entity data before saving.
- $callback : callable|null = null
-
A callback that will be invoked for newly created entities. This callback will be called before the entity is persisted.
- $options : array<string, mixed> = []
-
The options to use when saving.
Tags
Return values
EntityInterface —An entity.
findThreaded()
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.
public
findThreaded(Query $query, array<string, mixed> $options) : Query
Values belonging to a parent row based on their parent_id value will be
recursively nested inside the parent row values using the children
property
You can customize what fields are used for nesting results, by default the
primary key and the parent_id
fields are used. If you wish to change
these defaults you need to provide the keys keyField
, parentField
or nestingKey
in
$options
:
$table->find('threaded', [
'keyField' => 'id',
'parentField' => 'ancestor_id',
'nestingKey' => 'children'
]);
Parameters
- $query : Query
-
The query to find with
- $options : array<string, mixed>
-
The options to find with
Return values
Query —The query builder
fixName()
Fixes the name if we need to.
public
fixName(string $name) : string
Parameters
- $name : string
-
The string to fix.
Return values
string —The fixed name
fixNameCommon()
Common manipulation of an entity's name
public
fixNameCommon(string $name) : string
Parameters
- $name : string
-
The name to fix/normalize
Return values
string —The fixed name.
get()
Returns a single record after finding it by its primary key, if no record is found this method throws an exception.
public
get(mixed $primaryKey[, array<string, mixed> $options = [] ]) : EntityInterface
Usage
Get an article and some relationships:
$article = $articles->get(1, ['contain' => ['Users', 'Comments']]);
Parameters
- $primaryKey : mixed
-
primary key value to find
- $options : array<string, mixed> = []
-
options accepted by
Table::find()
Tags
Return values
EntityInterfaceget()
Returns a single record after finding it by its primary key, if no record is found this method throws an exception.
public
get([mixed $primaryKey = ][, array<string|int, mixed> $options = [] ]) : Course
Parameters
- $primaryKey : mixed =
-
primary key value to find
- $options : array<string|int, mixed> = []
-
options accepted by
Table::find()
Return values
CoursegetAlias()
Returns the table alias.
public
getAlias() : string
Return values
stringgetApplyError()
Gets an error is one happened.
public
getApplyError() : string
Return values
string —The error message.
getAssociation()
Returns an association object configured for the specified alias.
public
getAssociation(string $name) : Association
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
- $name : string
-
The alias used for the association.
Tags
Return values
Association —The association.
getBehavior()
Get a behavior from the registry.
public
getBehavior(string $name) : Behavior
Parameters
- $name : string
-
The behavior alias to get from the registry.
Tags
Return values
BehaviorgetCheckAdd()
Checks the checkadd cache and returns the id, or false
public
getCheckAdd(string $slug[, null|string $alias = null ]) : Entity|null
Parameters
- $slug : string
-
The slug to look up
- $alias : null|string = null
-
The model alias so look up.
Return values
Entity|null —This id if found, or false if not
getConnection()
Returns the connection instance.
public
getConnection() : Connection
Return values
ConnectiongetDisplayField()
Returns the display field.
public
getDisplayField() : array<string|int, string>|string|null
Return values
array<string|int, string>|string|nullgetEntityClass()
Returns the class used to hydrate rows for this table.
public
getEntityClass() : string
Tags
Return values
stringgetEventManager()
Returns the Cake\Event\EventManager manager instance for this object.
public
getEventManager() : EventManagerInterface
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.
Return values
EventManagerInterfacegetLastEntity()
Returns the last entity added to the cache
public
getLastEntity() : null|Entity
Return values
null|Entity —The last entity added to the cache
getMergeStats()
Get merge stats for a record to be deleted.
public
getMergeStats(int $id) : array<string, array<string, string|int>>
Parameters
- $id : int
-
The id of the record.
Return values
array<string, array<string, string|int>> —The list of stats.
getNameField()
Gets the nameField()
public
getNameField() : string
Return values
string —The field name for name
getPrimaryKey()
Returns the primary key field name.
public
getPrimaryKey() : array<string|int, string>|string
Return values
array<string|int, string>|stringgetRegistryAlias()
Returns the table registry key used to create this table instance.
public
getRegistryAlias() : string
Return values
stringgetSaveOptionsBuilder()
Gets a SaveOptionsBuilder instance.
public
getSaveOptionsBuilder([array<string, mixed> $options = [] ]) : SaveOptionsBuilder
Use a normal array for options instead.
Parameters
- $options : array<string, mixed> = []
-
Options to parse by the builder.
Return values
SaveOptionsBuildergetSchema()
Returns the schema table object describing this table's properties.
public
getSchema() : TableSchemaInterface
Return values
TableSchemaInterfacegetSlugField()
Gets the slugField()
public
getSlugField() : string
Return values
string —The field name for slug
getTable()
Returns the database table name.
public
getTable() : string
This can include the database schema name if set using setTable()
.
Return values
stringgetUseCache()
Gets if we're using memory caching.
public
getUseCache() : bool
Return values
bool —If we're using caching.
getValidator()
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.
public
getValidator([string|null $name = null ]) : Validator
If a validator has not been set earlier, this method will build a valiator using a method inside your class.
For example, if you wish to create a validation set called 'forSubscription', you will need to create a method in your Table subclass as follows:
public function validationForSubscription($validator)
{
return $validator
->add('email', 'valid-email', ['rule' => 'email'])
->add('password', 'valid', ['rule' => 'notBlank'])
->requirePresence('username');
}
$validator = $this->getValidator('forSubscription');
You can implement the method in validationDefault
in your Table subclass
should you wish to have a validation set that applies in cases where no other
set is specified.
If a $name argument has not been provided, the default validator will be returned.
You can configure your default validator name in a DEFAULT_VALIDATOR
class constant.
Parameters
- $name : string|null = null
-
The name of the validation set to return.
Return values
ValidatorhasAssociation()
Checks whether a specific association exists on this Table instance.
public
hasAssociation(string $name) : bool
The name argument also supports dot syntax to access deeper associations.
$hasUsers = $this->hasAssociation('Articles.Comments.Users');
Parameters
- $name : string
-
The alias used for the association.
Return values
boolhasBehavior()
Check if a behavior with the given alias has been loaded.
public
hasBehavior(string $name) : bool
Parameters
- $name : string
-
The behavior alias to check.
Return values
bool —Whether the behavior exists.
hasField()
Test to see if a Table has a specific field/column.
public
hasField(string $field) : bool
Delegates to the schema object and checks for column presence using the Schema\Table instance.
Parameters
- $field : string
-
The field to check for.
Return values
bool —True if the field exists, false if it does not.
hasFinder()
Returns true if the finder exists for the table
public
hasFinder(string $type) : bool
Parameters
- $type : string
-
name of finder to check
Return values
boolhasMany()
Creates a new HasMany association between this table and a target table. A "has many" association is a 1-N relationship.
public
hasMany(string $associated[, array<string, mixed> $options = [] ]) : HasMany
Target table can be inferred by its name, which is provided in the first argument, or you can either pass the class name to be instantiated or an instance of it directly.
The options array accept the following keys:
- className: The class name of the target table object
- targetTable: An instance of a table object to be used as the target table
- foreignKey: The name of the field to use as foreign key, if false none will be used
- dependent: Set to true if you want CakePHP to cascade deletes to the
associated table when an entity is removed on this table. The delete operation
on the associated table will not cascade further. To get recursive cascades enable
cascadeCallbacks
as well. Set to false if you don't want CakePHP to remove associated data, or when you are using database constraints. - cascadeCallbacks: Set to true if you want CakePHP to fire callbacks on cascaded deletes. If false the ORM will use deleteAll() to remove data. When true records will be loaded and then deleted.
- conditions: array with a list of conditions to filter the join with
- sort: The order in which results for this association should be returned
- saveStrategy: Either 'append' or 'replace'. When 'append' the current records
are appended to any records in the database. When 'replace' associated records
not in the current set will be removed. If the foreign key is a null able column
or if
dependent
is true records will be orphaned. - strategy: The strategy to be used for selecting results Either 'select' or 'subquery'. If subquery is selected the query used to return results in the source table will be used as conditions for getting rows in the target table.
- finder: The finder method to use when loading records from this association. Defaults to 'all'.
This method will return the association object that was built.
Parameters
- $associated : string
-
the alias for the target table. This is used to uniquely identify the association
- $options : array<string, mixed> = []
-
list of options to configure the association definition
Return values
HasManyhasOne()
Creates a new HasOne association between this table and a target table. A "has one" association is a 1-1 relationship.
public
hasOne(string $associated[, array<string, mixed> $options = [] ]) : HasOne
Target table can be inferred by its name, which is provided in the first argument, or you can either pass the class name to be instantiated or an instance of it directly.
The options array accept the following keys:
- className: The class name of the target table object
- targetTable: An instance of a table object to be used as the target table
- foreignKey: The name of the field to use as foreign key, if false none will be used
- dependent: Set to true if you want CakePHP to cascade deletes to the
associated table when an entity is removed on this table. The delete operation
on the associated table will not cascade further. To get recursive cascades enable
cascadeCallbacks
as well. Set to false if you don't want CakePHP to remove associated data, or when you are using database constraints. - cascadeCallbacks: Set to true if you want CakePHP to fire callbacks on cascaded deletes. If false the ORM will use deleteAll() to remove data. When true records will be loaded and then deleted.
- conditions: array with a list of conditions to filter the join with
- joinType: The type of join to be used (e.g. LEFT)
- strategy: The loading strategy to use. 'join' and 'select' are supported.
- finder: The finder method to use when loading records from this association. Defaults to 'all'. When the strategy is 'join', only the fields, containments, and where conditions will be used from the finder.
This method will return the association object that was built.
Parameters
- $associated : string
-
the alias for the target table. This is used to uniquely identify the association
- $options : array<string, mixed> = []
-
list of options to configure the association definition
Return values
HasOnehasValidator()
Checks whether a validator has been set.
public
hasValidator(string $name) : bool
Parameters
- $name : string
-
The name of a validator.
Return values
boolimplementedEvents()
Get the Model callbacks this table is interested in.
public
implementedEvents() : array<string, mixed>
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
Return values
array<string, mixed>initCheckAdd()
Initialize method
public
initCheckAdd([array<string, mixed> $config = [] ]) : void
Parameters
- $config : array<string, mixed> = []
-
The configuration for the Table.
initialize()
Initialize method
public
initialize([array<string|int, mixed> $config = [] ]) : void
Parameters
- $config : array<string|int, mixed> = []
-
The configuration for the Table.
loadInto()
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.
public
loadInto(EntityInterface|array<string|int, EntityInterface> $entities, array<string|int, mixed> $contain) : EntityInterface|array<string|int, EntityInterface>
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
- $entities : EntityInterface|array<string|int, EntityInterface>
-
a single entity or list of entities
- $contain : array<string|int, mixed>
-
A
contain()
compatible array.
Tags
Return values
EntityInterface|array<string|int, EntityInterface>marshaller()
Get the object used to marshal/convert array data into objects.
public
marshaller() : Marshaller
Override this method if you want a table object to use custom marshalling logic.
Tags
Return values
MarshallermergeDelete()
Allows to merge associated records from one attribute to another, then delete the old record.
public
mergeDelete(int $sourceId, int $targetId) : bool
Parameters
- $sourceId : int
-
The record id to delete.
- $targetId : int
-
The record id to move the associated records to.
Tags
Return values
bool —If the save was successfull.
newEmptyEntity()
This creates a new entity object.
public
newEmptyEntity() : EntityInterface
Return values
EntityInterfacenewEntities()
Create a list of entities + associated entities from an array.
public
newEntities(array<string|int, mixed> $data[, array<string, mixed> $options = [] ]) : array<string|int, EntityInterface>
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
- $data : array<string|int, mixed>
-
The data to build an entity with.
- $options : array<string, mixed> = []
-
A list of options for the objects hydration.
Return values
array<string|int, EntityInterface> —An array of hydrated records.
newEntity()
Create a new entity + associated entities from an array.
public
newEntity(array<string|int, mixed> $data[, array<string, mixed> $options = [] ]) : EntityInterface
By default all the associations on this table will be hydrated. You can limit which associations are built, or include deeper associations using the options parameter:
$article = $this->Articles->newEntity(
$this->request->getData(),
['associated' => ['Tags', 'Comments.Users']]
);
You can limit fields that will be present in the constructed entity by
passing the fields
option, which is also accepted for associations:
$article = $this->Articles->newEntity($this->request->getData(), [
'fields' => ['title', 'body', 'tags', 'comments'],
'associated' => ['Tags', 'Comments.Users' => ['fields' => 'username']]
]
);
The fields
option lets remove or restrict input data from ending up in
the entity. If you'd like to relax the entity's default accessible fields,
you can use the accessibleFields
option:
$article = $this->Articles->newEntity(
$this->request->getData(),
['accessibleFields' => ['protected_field' => true]]
);
By default, the data is validated before being passed to the new entity. In
the case of invalid fields, those will not be present in the resulting object.
The validate
option can be used to disable validation on the passed data:
$article = $this->Articles->newEntity(
$this->request->getData(),
['validate' => false]
);
You can also pass the name of the validator to use in the validate
option.
If null
is passed to the first param of this function, no validation will
be performed.
You can use the Model.beforeMarshal
event to modify request data
before it is converted into entities.
Parameters
- $data : array<string|int, mixed>
-
The data to build an entity with.
- $options : array<string, mixed> = []
-
A list of options for the object hydration.
Tags
Return values
EntityInterfacenewEntity()
Create a new entity + associated entities from an array.
public
newEntity([mixed $data = null ][, array<string|int, mixed> $options = [] ]) : Course
Parameters
- $data : mixed = null
-
The data to build an entity with.
- $options : array<string|int, mixed> = []
-
A list of options for the object hydration.
Return values
CoursepatchEntities()
Merges each of the elements passed in `$data` into the entities found in `$entities` respecting the accessible fields configured on the entities.
public
patchEntities(iterable<string|int, EntityInterface> $entities, array<string|int, mixed> $data[, array<string, mixed> $options = [] ]) : array<string|int, EntityInterface>
Those entries in $entities
that cannot be matched to any record in
$data
will be discarded. Records in $data
that could not be matched will
be marshalled as a new entity.
When merging HasMany or BelongsToMany associations, all the entities in the
$data
array will appear, those that can be matched by primary key will get
the data merged, but those that cannot, will be discarded.
You can limit fields that will be present in the merged entities by
passing the fields
option, which is also accepted for associations:
$articles = $this->Articles->patchEntities($articles, $this->request->getData(), [
'fields' => ['title', 'body', 'tags', 'comments'],
'associated' => ['Tags', 'Comments.Users' => ['fields' => 'username']]
]
);
You can use the Model.beforeMarshal
event to modify request data
before it is converted into entities.
Parameters
- $entities : iterable<string|int, EntityInterface>
-
the entities that will get the data merged in
- $data : array<string|int, mixed>
-
list of arrays to be merged into the entities
- $options : array<string, mixed> = []
-
A list of options for the objects hydration.
Return values
array<string|int, EntityInterface>patchEntity()
Merges the passed `$data` into `$entity` respecting the accessible fields configured on the entity. Returns the same entity after being altered.
public
patchEntity(EntityInterface $entity, array<string|int, mixed> $data[, array<string, mixed> $options = [] ]) : EntityInterface
When merging HasMany or BelongsToMany associations, all the entities in the
$data
array will appear, those that can be matched by primary key will get
the data merged, but those that cannot, will be discarded.
You can limit fields that will be present in the merged entity by
passing the fields
option, which is also accepted for associations:
$article = $this->Articles->patchEntity($article, $this->request->getData(), [
'fields' => ['title', 'body', 'tags', 'comments'],
'associated' => ['Tags', 'Comments.Users' => ['fields' => 'username']]
]
);
$article = $this->Articles->patchEntity($article, $this->request->getData(), [
'associated' => [
'Tags' => ['accessibleFields' => ['*' => true]]
]
]);
By default, the data is validated before being passed to the entity. In
the case of invalid fields, those will not be assigned to the entity.
The validate
option can be used to disable validation on the passed data:
$article = $this->patchEntity($article, $this->request->getData(),[
'validate' => false
]);
You can use the Model.beforeMarshal
event to modify request data
before it is converted into entities.
When patching scalar values (null/booleans/string/integer/float), if the property presently has an identical value, the setter will not be called, and the property will not be marked as dirty. This is an optimization to prevent unnecessary field updates when persisting entities.
Parameters
- $entity : EntityInterface
-
the entity that will get the data merged in
- $data : array<string|int, mixed>
-
key value list of fields to be merged into the entity
- $options : array<string, mixed> = []
-
A list of options for the object hydration.
Tags
Return values
EntityInterfacequery()
Creates a new Query instance for a table.
public
query() : Query
Return values
QueryremoveBehavior()
Removes a behavior from this table's behavior registry.
public
removeBehavior(string $name) : $this
Example:
Remove a behavior from this table.
$this->removeBehavior('Tree');
Parameters
- $name : string
-
The alias that the behavior was added with.
Tags
Return values
$thisrulesChecker()
Returns the RulesChecker for this instance.
public
rulesChecker() : RulesChecker
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.
Tags
Return values
RulesCheckersave()
Persists an entity based on the fields that are marked as dirty and returns the same entity after a successful save or false in case of any error.
public
save(EntityInterface $entity[, SaveOptionsBuilder|ArrayAccess|array<string|int, mixed> $options = [] ]) : EntityInterface|false
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
true
it will save 1st level associated entities as they are found in the passed$entity
whenever the property defined for the association is marked as dirty. If an array, it will be interpreted as the list of associations to be saved. It is possible to provide different options for saving on associated table objects using this key by making the custom options the array value. Iffalse
no 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
checkRules
key in $options is not set to false. Listeners will receive as arguments the entity, options array and the operation type. If the event is stopped the rules check result will be set to the result of the event itself. - Model.afterRules: Will be triggered right after the
checkRules()
method is called for the entity. Listeners will receive as arguments the entity, options array, the result of checking the rules and the operation type. If the event is stopped the checking result will be set to the result of the event itself. - Model.beforeSave: Will be triggered just before the list of fields to be
persisted is calculated. It receives both the entity and the options as
arguments. The options array is passed as an ArrayObject, so any changes in
it will be reflected in every listener and remembered at the end of the event
so it can be used for the rest of the save operation. Returning false in any
of the listeners will abort the saving process. If the event is stopped
using the event API, the event object's
result
property will be returned. This can be useful when having your own saving strategy implemented inside a listener. - Model.afterSave: Will be triggered after a successful insert or save,
listeners will receive the entity and the options array as arguments. The type
of operation performed (insert or update) can be determined by checking the
entity's method
isNew
, true meaning an insert and false an update. - Model.afterSaveCommit: Will be triggered after the transaction is 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' => [
'associated' => ['Addresses'],
'checkRules' => false
]
]
]);
// Save no associations
$articles->save($entity, ['associated' => false]);
Parameters
- $entity : EntityInterface
-
the entity to be saved
- $options : SaveOptionsBuilder|ArrayAccess|array<string|int, mixed> = []
-
The options to use when saving.
Tags
Return values
EntityInterface|falsesaveMany()
Persists multiple entities of a table.
public
saveMany(iterable<string|int, EntityInterface> $entities[, SaveOptionsBuilder|ArrayAccess|array<string|int, mixed> $options = [] ]) : iterable<string|int, EntityInterface>|false
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.
Parameters
- $entities : iterable<string|int, EntityInterface>
-
Entities to save.
- $options : SaveOptionsBuilder|ArrayAccess|array<string|int, mixed> = []
-
Options used when calling Table::save() for each entity.
Tags
Return values
iterable<string|int, EntityInterface>|false —False on failure, entities list on success.
saveManyOrFail()
Persists multiple entities of a table.
public
saveManyOrFail(iterable<string|int, EntityInterface> $entities[, ArrayAccess|array<string|int, mixed> $options = [] ]) : iterable<string|int, EntityInterface>
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.
Parameters
- $entities : iterable<string|int, EntityInterface>
-
Entities to save.
- $options : ArrayAccess|array<string|int, mixed> = []
-
Options used when calling Table::save() for each entity.
Tags
Return values
iterable<string|int, EntityInterface> —Entities list.
saveOrFail()
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.
public
saveOrFail(EntityInterface $entity[, ArrayAccess|array<string|int, mixed> $options = [] ]) : EntityInterface
Parameters
- $entity : EntityInterface
-
the entity to be saved
- $options : ArrayAccess|array<string|int, mixed> = []
-
The options to use when saving.
Tags
Return values
EntityInterfacesaveOrFail()
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.
public
saveOrFail([Course|Entity $entity = ][, array<string|int, mixed> $options = [] ]) : Course
Parameters
- $entity : Course|Entity =
-
the entity to be saved
- $options : array<string|int, mixed> = []
-
The options to use when saving.
Return values
CoursesetAlias()
Sets the table alias.
public
setAlias(string $alias) : $this
Parameters
- $alias : string
-
Table alias
Return values
$thissetApplyError()
Sets an error if one happens.
public
setApplyError(string $msg) : void
Parameters
- $msg : string
-
The error message.
setCheckAdd()
Adds the id to the checkadd cache
public
setCheckAdd(string $slug, Entity $entity[, null|string $alias = null ]) : Entity
Parameters
- $slug : string
-
The slug to look up
- $entity : Entity
-
The object record that was added
- $alias : null|string = null
-
The model alias so look up.
Return values
EntitysetConnection()
Sets the connection instance.
public
setConnection(Connection $connection) : $this
Parameters
- $connection : Connection
-
The connection instance
Return values
$thissetDisplayField()
Sets the display field.
public
setDisplayField(array<string|int, string>|string $field) : $this
Parameters
- $field : array<string|int, string>|string
-
Name to be used as display field.
Return values
$thissetEntityClass()
Sets the class used to hydrate rows for this table.
public
setEntityClass(string $name) : $this
Parameters
- $name : string
-
The name of the class to use
Tags
Return values
$thissetEventManager()
Returns the Cake\Event\EventManagerInterface instance for this object.
public
setEventManager(EventManagerInterface $eventManager) : $this
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
- $eventManager : EventManagerInterface
-
the eventManager to set
Return values
$thissetLastEntity()
Sets tracking on the last entity that was added to the cache
public
setLastEntity(Entity $entity) : void
Parameters
- $entity : Entity
-
The last entity added to the cache
setNameField()
Sets the name field, if different from the default
public
setNameField(string $field) : void
Parameters
- $field : string
-
The field name to have the name set to
setPrimaryKey()
Sets the primary key field name.
public
setPrimaryKey(array<string|int, string>|string $key) : $this
Parameters
- $key : array<string|int, string>|string
-
Sets a new name to be used as primary key
Return values
$thissetRegistryAlias()
Sets the table registry key used to create this table instance.
public
setRegistryAlias(string $registryAlias) : $this
Parameters
- $registryAlias : string
-
The key used to access this object.
Return values
$thissetSchema()
Sets the schema table object describing this table's properties.
public
setSchema(TableSchemaInterface|array<string|int, mixed> $schema) : $this
If an array is passed, a new TableSchemaInterface will be constructed out of it and used as the schema for this table.
Parameters
- $schema : TableSchemaInterface|array<string|int, mixed>
-
Schema to be used for this table
Return values
$thissetSlugField()
Sets the slug field, if different from the default
public
setSlugField(string $field) : void
Parameters
- $field : string
-
The field name to have the slug set to
setTable()
Sets the database table name.
public
setTable(string $table) : $this
This can include the database schema name in the form 'schema.table'. If the name must be quoted, enable automatic identifier quoting.
Parameters
- $table : string
-
Table name.
Return values
$thissetUseCache()
Sets if we're using memory caching.
public
setUseCache([bool $toCache = false ]) : void
Parameters
- $toCache : bool = false
-
Set whether or not to use memory caching.
setValidator()
This method stores a custom validator under the given name.
public
setValidator(string $name, Validator $validator) : $this
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
- $name : string
-
The name of a validator to be set.
- $validator : Validator
-
Validator object to be set.
Return values
$thisslugify()
Creates a slug from the input
public
slugify([mixed $input = null ]) : string
Parameters
- $input : mixed = null
-
The input to create the slug from
Tags
Return values
string —the slugged string
subquery()
Creates a new Query::subquery() instance for a table.
public
subquery() : Query
Tags
Return values
Querytoggle()
Allows toggling of boolean fields.
public
toggle(int $id, string $field) : bool
Parameters
- $id : int
-
The record id to update.
- $field : string
-
The field to toggle.
Tags
Return values
bool —The set toggled value
updateAll()
Update all matching records.
public
updateAll(mixed $fields, mixed $conditions) : int
Parameters
- $fields : mixed
-
A hash of field => new value.
- $conditions : mixed
-
Conditions to be used, accepts anything Query::where() can take.
Tags
Return values
int —Count Returns the affected rows.
validateUnique()
Validator method used to check the uniqueness of a value for a column.
public
validateUnique(mixed $value, array<string, mixed> $options[, array<string|int, mixed>|null $context = null ]) : bool
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
- $value : mixed
-
The value of column to be checked for uniqueness.
- $options : array<string, mixed>
-
The options array, optionally containing the 'scope' key. May also be the validation context, if there are no options.
- $context : array<string|int, mixed>|null = null
-
Either the validation context or null.
Return values
bool —True if the value is unique, or false if a non-scalar, non-unique value was given.
validationDefault()
Returns the default validator object. Subclasses can override this function to add a default validation set to the validator object.
public
validationDefault(Validator $validator) : Validator
Parameters
- $validator : Validator
-
The validator that can be modified to add some rules to it.
Return values
Validator_deleteMany()
protected
_deleteMany(iterable<string|int, EntityInterface> $entities[, ArrayAccess|array<string|int, mixed> $options = [] ]) : EntityInterface|null
Parameters
- $entities : iterable<string|int, EntityInterface>
-
Entities to delete.
- $options : ArrayAccess|array<string|int, mixed> = []
-
Options used.
Return values
EntityInterface|null_dynamicFinder()
Provides the dynamic findBy and findAllBy methods.
protected
_dynamicFinder(string $method, array<string|int, mixed> $args) : Query
Parameters
- $method : string
-
The method name that was fired.
- $args : array<string|int, mixed>
-
List of arguments passed to the function.
Tags
Return values
Query_executeTransaction()
Handles the logic executing of a worker inside a transaction.
protected
_executeTransaction(callable $worker[, bool $atomic = true ]) : mixed
Parameters
- $worker : callable
-
The worker that will run inside the transaction.
- $atomic : bool = true
-
Whether to execute the worker inside a database transaction.
_getFindOrCreateQuery()
Gets the query object for findOrCreate().
protected
_getFindOrCreateQuery(Query|callable|array<string|int, mixed> $search) : Query
Parameters
- $search : Query|callable|array<string|int, mixed>
-
The criteria to find existing records by.
Return values
Query_initializeSchema()
Override this function in order to alter the schema used by this table.
protected
_initializeSchema(TableSchemaInterface $schema) : TableSchemaInterface
This function is only called after fetching the schema out of the database. If you wish to provide your own schema to this table without touching the database, you can override schema() or inject the definitions though that method.
Example:
protected function _initializeSchema(\Cake\Database\Schema\TableSchemaInterface $schema) {
$schema->setColumnType('preferences', 'json');
return $schema;
}
Parameters
- $schema : TableSchemaInterface
-
The table definition fetched from database.
Return values
TableSchemaInterface —the altered schema
_insert()
Auxiliary function to handle the insert of an entity's data in the table
protected
_insert(EntityInterface $entity, array<string|int, mixed> $data) : EntityInterface|false
Parameters
- $entity : EntityInterface
-
the subject entity from were $data was extracted
- $data : array<string|int, mixed>
-
The actual data that needs to be saved
Tags
Return values
EntityInterface|false_newId()
Generate a primary key value for a new record.
protected
_newId(array<string|int, string> $primary) : string|null
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
- $primary : array<string|int, string>
-
The primary key columns to get a new ID for.
Return values
string|null —Either null or the primary key value or a list of primary key values.
_onSaveSuccess()
Handles the saving of children associations and executing the afterSave logic once the entity for this table has been saved successfully.
protected
_onSaveSuccess(EntityInterface $entity, ArrayObject $options) : bool
Parameters
- $entity : EntityInterface
-
the entity to be saved
- $options : ArrayObject
-
the options to use for the save operation
Tags
Return values
bool —True on success
_processDelete()
Perform the delete operation.
protected
_processDelete(EntityInterface $entity, ArrayObject $options) : bool
Will delete the entity provided. Will remove rows from any dependent associations, and clear out join tables for BelongsToMany associations.
Parameters
- $entity : EntityInterface
-
The entity to delete.
- $options : ArrayObject
-
The options for the delete.
Tags
Return values
bool —success
_processFindOrCreate()
Performs the actual find and/or create of an entity based on the passed options.
protected
_processFindOrCreate(Query|callable|array<string|int, mixed> $search[, callable|null $callback = null ][, array<string, mixed> $options = [] ]) : EntityInterface|array<string|int, mixed>
Parameters
- $search : Query|callable|array<string|int, mixed>
-
The criteria to find an existing record by, or a callable tha will customize the find query.
- $callback : callable|null = null
-
A callback that will be invoked for newly created entities. This callback will be called before the entity is persisted.
- $options : array<string, mixed> = []
-
The options to use when saving.
Tags
Return values
EntityInterface|array<string|int, mixed> —An entity.
_processSave()
Performs the actual saving of an entity based on the passed options.
protected
_processSave(EntityInterface $entity, ArrayObject $options) : EntityInterface|false
Parameters
- $entity : EntityInterface
-
the entity to be saved
- $options : ArrayObject
-
the options to use for the save operation
Tags
Return values
EntityInterface|false_saveMany()
protected
_saveMany(iterable<string|int, EntityInterface> $entities[, SaveOptionsBuilder|ArrayAccess|array<string|int, mixed> $options = [] ]) : iterable<string|int, EntityInterface>
Parameters
- $entities : iterable<string|int, EntityInterface>
-
Entities to save.
- $options : SaveOptionsBuilder|ArrayAccess|array<string|int, mixed> = []
-
Options used when calling Table::save() for each entity.
Tags
Return values
iterable<string|int, EntityInterface> —Entities list.
_setFieldMatchers()
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.
protected
_setFieldMatchers(array<string, mixed> $options, array<string|int, string> $keys) : array<string, mixed>
This is an auxiliary function used for result formatters that can accept composite keys when comparing values.
Parameters
- $options : array<string, mixed>
-
the original options passed to a finder
- $keys : array<string|int, string>
-
the keys to check in $options to build matchers from the associated value
Return values
array<string, mixed>_transactionCommitted()
Checks if the caller would have executed a commit on a transaction.
protected
_transactionCommitted(bool $atomic, bool $primary) : bool
Parameters
- $atomic : bool
-
True if an atomic transaction was used.
- $primary : bool
-
True if a primary was used.
Return values
bool —Returns true if a transaction was committed.
_update()
Auxiliary function to handle the update of an entity's data in the table
protected
_update(EntityInterface $entity, array<string|int, mixed> $data) : EntityInterface|false
Parameters
- $entity : EntityInterface
-
the subject entity from were $data was extracted
- $data : array<string|int, mixed>
-
The actual data that needs to be saved
Tags
Return values
EntityInterface|falsecheckAliasLengths()
Checks if all table name + column name combinations used for queries fit into the max length allowed by database driver.
protected
checkAliasLengths() : void
Tags
createValidator()
Creates a validator using a custom method inside your class.
protected
createValidator(string $name) : Validator
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
- $name : string
-
The name of the validation set to create.
Tags
Return values
ValidatorfindAssociation()
Returns an association object configured for the specified alias if any.
protected
findAssociation(string $name) : Association|null
The name argument also supports dot syntax to access deeper associations.
$users = $this->getAssociation('Articles.Comments.Users');
Parameters
- $name : string
-
The alias used for the association.
Return values
Association|null —Either the association or null.
validationMethodExists()
protected
validationMethodExists(string $name) : bool
Parameters
- $name : string