Class BelongsToMany
Represents an M - N relationship where there exists a junction - or join - table that contains the association fields between the source and the target table.
An example of a BelongsToMany association would be Article belongs to many Tags.
Constants
-
string
MANY_TO_MANY ¶'manyToMany'
Association type for many to many associations.
-
string
MANY_TO_ONE ¶'manyToOne'
Association type for many to one associations.
-
string
ONE_TO_MANY ¶'oneToMany'
Association type for one to many associations.
-
string
ONE_TO_ONE ¶'oneToOne'
Association type for one to one associations.
-
string
SAVE_APPEND ¶'append'
Saving strategy that will only append to the links set
-
string
SAVE_REPLACE ¶'replace'
Saving strategy that will replace the links with the provided set
-
string
STRATEGY_JOIN ¶'join'
Strategy name to use joins for fetching associated records
-
string
STRATEGY_SELECT ¶'select'
Strategy name to use a select for fetching associated records
-
string
STRATEGY_SUBQUERY ¶'subquery'
Strategy name to use a subquery for fetching associated records
Property Summary
-
$_bindingKey protected
string|array
The field name in the owning side table that is used to match with the foreignKey
-
$_cascadeCallbacks protected
string
Whether or not cascaded deletes should also fire callbacks.
-
$_className protected
string
The class name of the target table object
-
$_conditions protected
array
A list of conditions to be always included when fetching records from the target association
-
$_dependent protected
bool
Whether the records on the joint table should be removed when a record on the source table is deleted.
-
$_finder protected
string
The default finder name to use for fetching rows from the target table
-
$_foreignKey protected
string|array
The name of the field representing the foreign key to the table to load
-
$_joinType protected
string
The type of join to be used when adding the association to a query
-
$_junctionAssociationName protected
string
The name of the hasMany association from the target table to the junction table
-
$_junctionProperty protected
string
The name of the property to be set containing data from the junction table once a record from the target table is hydrated
-
$_junctionTable protected
Cake\ORM\Table
Junction table instance
-
$_junctionTableName protected
string
Junction table name
-
$_name protected
string
Name given to the association, it usually represents the alias assigned to the target associated table
-
$_propertyName protected
string
The property name that should be filled with data from the target table in the source table record.
-
$_saveStrategy protected
string
Saving strategy to be used by this association
-
$_sort protected
mixed
Order in which target records should be returned
-
$_sourceTable protected
Cake\ORM\Table
Source table instance
-
$_strategy protected
string
The strategy name to be used to fetch associated records.
-
$_targetForeignKey protected
string|array
The name of the field representing the foreign key to the target table
-
$_targetTable protected
Cake\ORM\Table
Target table instance
-
$_through protected
stringCake\ORM\Table
The table instance for the junction relation.
-
$_validStrategies protected
array
Valid strategies for this type of association
Method Summary
-
__call() public
Proxies method calls to the target table.
-
__construct() public
Constructor. Subclasses can override _options function to get the original list of passed options if expecting any other special key
-
__get() public
Proxies property retrieval to the target table. This is handy for getting this association's associations
-
__isset() public
Proxies the isset call to the target table. This is handy to check if the target table has another association with the passed name
-
_addFilteringCondition() protected
Appends any conditions required to load the relevant set of records in the target table query given a filter key and some filtering values.
-
_addFilteringJoin() public
Appends any conditions required to load the relevant set of records in the target table query given a filter key and some filtering values when the filtering needs to be done using a subquery.
-
_appendFields() protected
Helper function used to conditionally append fields to the select clause of a query from the fields found in another query object.
-
_bindNewAssociations() protected
Applies all attachable associations to
$query
out of the containments found in the$surrogate
query. -
_buildQuery() protected
Auxiliary function to construct a new Query object to return all the records in the target table that are associated to those specified in $options from the source table.
-
_buildResultMap() protected
Builds an array containing the results from fetchQuery indexed by the foreignKey value corresponding to this association.
-
_buildSubquery() protected
Builds a query to be used as a condition for filtering records in the target table, it is constructed by cloning the original query that was used to load records in the source table.
-
_camelize() protected
Creates a camelized version of $name
-
_checkPersistenceStatus() protected
Throws an exception should any of the passed entities is not persisted.
-
_collectJointEntities() protected
Returns the list of joint entities that exist between the source entity and each of the passed target entities
-
_createTupleCondition() protected
Returns a TupleComparison object that can be used for matching all the fields from $keys with the tuple values in $filter using the provided operator.
-
_defaultOptions() protected
Returns the default options to use for the eagerLoader
-
_diffLinks() protected
Helper method used to delete the difference between the links passed in
$existing
and$jointEntities
. This method will return the values from$targetEntities
that were not deleted from calculating the difference. -
_dispatchBeforeFind() protected
Triggers beforeFind on the target table for the query this association is attaching to
-
_entityName() protected
Creates the proper entity name (singular) for the specified name
-
_extractFinder() protected
Helper method to infer the requested finder and its options.
-
_fixtureName() protected
Creates a fixture name
-
_formatAssociationResults() protected
Adds a formatter function to the passed
$query
if the$surrogate
query declares any other formatter. Since the$surrogate
query correspond to the associated target table, the resulting formatter will be the result of applying the surrogate formatters to only the property corresponding to such table. -
_joinCondition() protected
Return false as join conditions are defined in the junction table
-
_junctionAssociationName() protected
Returns the name of the association from the target table to the junction table, this name is used to generate alias in the query and to later on retrieve the results.
-
_junctionTableName() protected
Sets the name of the junction table. If no arguments are passed the current configured name is returned. A default name based of the associated tables will be generated if none found.
-
_linkField() protected
Generates a string used as a table field that contains the values upon which the filter should be applied
-
_modelKey() protected
Creates the proper underscored model key for associations
-
_modelNameFromKey() protected
Creates the proper model name from a foreign key
-
_multiKeysInjector() protected
Returns a callable to be used for each row in a query result set for injecting the eager loaded rows when the matching needs to be done with multiple foreign keys
-
_options() protected
Parse extra options passed in the constructor.
-
_pluginNamespace() protected
Return plugin's namespace
-
_pluginPath() protected
Find the correct path for a plugin. Scans $pluginPaths for the plugin you want.
-
_pluralHumanName() protected
Creates the plural human name used in views
-
_resultInjector() protected
Returns a callable to be used for each row in a query result set for injecting the eager loaded rows
-
_saveLinks() protected
Creates links between the source entity and each of the passed target entities
-
_saveTarget() protected
Persists each of the entities into the target table and creates links between the parent entity and each one of the saved target entities.
-
_singularHumanName() protected
Creates the singular human name used in views
-
_singularName() protected
Creates the singular name for use in views.
-
_variableName() protected
Creates the plural variable name for views
-
attachTo() public
Alters a Query object to include the associated target table data in the final result
-
bindingKey() public
Sets the name of the field representing the binding field with the target table. When not manually specified the primary key of the owning side table is used.
-
canBeJoined() public
Whether this association can be expressed directly in a query join
-
cascadeCallbacks() public
Sets whether or not cascaded deletes should also fire callbacks. If no arguments are passed, the current configured value is returned
-
cascadeDelete() public
Clear out the data in the junction table for a given entity.
-
conditions() public
Sets a list of conditions to be always included when fetching records from the target association. If no parameters are passed the current list is returned
-
defaultRowValue() public
Returns a modified row after appending a property for this association with the default empty value according to whether the association was joined or fetched externally.
-
deleteAll() public
Proxies the delete operation to the target table's deleteAll method
-
dependent() public
Sets whether the records on the target table are dependent on the source table.
-
eagerLoader() public
Eager loads a list of records in the target table that are related to another set of records in the source table. Source records can specified in two ways: first one is by passing a Query object setup to find on the source table and the other way is by explicitly passing an array of primary key values from the source table.
-
find() public
Proxies the finding operation to the target table's find method and modifies the query accordingly based of this association configuration
-
finder() public
Sets the default finder to use for fetching rows from the target table. If no parameters are passed, it will return the currently configured finder name.
-
foreignKey() public
Sets the name of the field representing the foreign key to the source table. If no parameters are passed current field is returned
-
isOwningSide() public
Returns boolean true, as both of the tables 'own' rows in the other side of the association via the joint table.
-
joinType() public
Sets the type of join to be used when adding the association to a query. If no arguments are passed, the currently configured type is returned.
-
junction() public
Sets the table instance for the junction relation. If no arguments are passed, the current configured table instance is returned
-
link() public
Associates the source entity to each of the target entities provided by creating links in the junction table. Both the source entity and each of the target entities are assumed to be already persisted, if the are marked as new or their status is unknown, an exception will be thrown.
-
name() public
Sets the name for this association. If no argument is passed then the current configured name will be returned
-
property() public
Sets the property name that should be filled with data from the target table in the source table record. If no arguments are passed, the currently configured type is returned.
-
replaceLinks() public
Replaces existing association links between the source entity and the target with the ones passed. This method does a smart cleanup, links that are already persisted and present in
$targetEntities
will not be deleted, new links will be created for the passed target entities that are not already in the database and the rest will be removed. -
requiresKeys() public
Returns true if the eager loading process will require a set of the owning table's binding keys in order to use them as a filter in the finder query.
-
saveAssociated() public
Takes an entity from the source table and looks if there is a field matching the property name for this association. The found entity will be saved on the target table for this association by passing supplied
$options
-
saveStrategy() public
Sets the strategy that should be used for saving. If called with no arguments, it will return the currently configured strategy
-
sort() public
Sets the sort order in which target records should be returned. If no arguments are passed the currently configured value is returned
-
source() public
Sets the table instance for the source side of the association. If no arguments are passed, the current configured table instance is returned
-
strategy() public
Sets the strategy name to be used to fetch associated records. Keep in mind that some association types might not implement but a default strategy, rendering any changes to this setting void. If no arguments are passed, the currently configured strategy is returned.
-
target() public
Sets the table instance for the target side of the association. If no arguments are passed, the current configured table instance is returned
-
targetForeignKey() public
Sets the name of the field representing the foreign key to the target table. If no parameters are passed current field is returned
-
transformRow() public
Correctly nests a result row associated values into the correct array keys inside the source results.
-
type() public
Get the relationship type.
-
unlink() public
Removes all links between the passed source entity and each of the provided target entities. This method assumes that all passed objects are already persisted in the database and that each of them contain a primary key value.
-
updateAll() public
Proxies the update operation to the target table's updateAll method
Method Detail
__call() ¶ public
__call(string $method, array $argument): mixed
Proxies method calls to the target table.
Parameters
-
string
$method name of the method to be invoked
-
array
$argument List of arguments passed to the function
Returns
mixed
Throws
BadMethodCallException
__construct() ¶ public
__construct(string $alias, array $options = [])
Constructor. Subclasses can override _options function to get the original list of passed options if expecting any other special key
Parameters
-
string
$alias The name given to the association
-
array
$options optional A list of properties to be set on this object
__get() ¶ public
__get(string $property): Cake\ORM\Association
Proxies property retrieval to the target table. This is handy for getting this association's associations
Parameters
-
string
$property the property name
Returns
Cake\ORM\Association
Throws
RuntimeException
if no association with such name exists
__isset() ¶ public
__isset(string $property): bool
Proxies the isset call to the target table. This is handy to check if the target table has another association with the passed name
Parameters
-
string
$property the property name
Returns
bool
_addFilteringCondition() ¶ protected
_addFilteringCondition(Cake\ORM\Query $query, string|array $key, mixed $filter): Cake\ORM\Query
Appends any conditions required to load the relevant set of records in the target table query given a filter key and some filtering values.
Parameters
-
Cake\ORM\Query
$query Target table's query
-
string|array
$key the fields that should be used for filtering
-
mixed
$filter the value that should be used to match for $key
Returns
Cake\ORM\Query
_addFilteringJoin() ¶ public
_addFilteringJoin(Cake\ORM\Query $query, string $key, Cake\ORM\Query $subquery): Cake\ORM\Query
Appends any conditions required to load the relevant set of records in the target table query given a filter key and some filtering values when the filtering needs to be done using a subquery.
Parameters
-
Cake\ORM\Query
$query Target table's query
-
string
$key the fields that should be used for filtering
-
Cake\ORM\Query
$subquery The Subquery to use for filtering
Returns
Cake\ORM\Query
_appendFields() ¶ protected
_appendFields(Cake\ORM\Query $query, Cake\ORM\Query $surrogate, array $options): void
Helper function used to conditionally append fields to the select clause of a query from the fields found in another query object.
Parameters
-
Cake\ORM\Query
$query the query that will get the fields appended to
-
Cake\ORM\Query
$surrogate the query having the fields to be copied from
-
array
$options options passed to the method
attachTo
Returns
void
_bindNewAssociations() ¶ protected
_bindNewAssociations(Cake\ORM\Query $query, Cake\ORM\Query $surrogate, array $options): void
Applies all attachable associations to $query
out of the containments found
in the $surrogate
query.
Copies all contained associations from the $surrogate
query into the
passed $query
. Containments are altered so that they respect the associations
chain from which they originated.
Parameters
-
Cake\ORM\Query
$query the query that will get the associations attached to
-
Cake\ORM\Query
$surrogate the query having the containments to be attached
-
array
$options options passed to the method
attachTo
Returns
void
_buildQuery() ¶ protected
_buildQuery(array $options): Cake\ORM\Query
Auxiliary function to construct a new Query object to return all the records in the target table that are associated to those specified in $options from the source table.
This is used for eager loading records on the target table based on conditions.
Parameters
-
array
$options options accepted by eagerLoader()
Returns
Cake\ORM\Query
Throws
InvalidArgumentException
When a key is required for associations but not selected.
_buildResultMap() ¶ protected
_buildResultMap(Cake\ORM\Query $fetchQuery, array $options): array
Builds an array containing the results from fetchQuery indexed by the foreignKey value corresponding to this association.
Parameters
-
Cake\ORM\Query
$fetchQuery The query to get results from
-
array
$options The options passed to the eager loader
Returns
array
Throws
RuntimeException
when the association property is not part of the results set.
_buildSubquery() ¶ protected
_buildSubquery(Cake\ORM\Query $query): Cake\ORM\Query
Builds a query to be used as a condition for filtering records in the target table, it is constructed by cloning the original query that was used to load records in the source table.
Parameters
-
Cake\ORM\Query
$query the original query used to load source records
Returns
Cake\ORM\Query
_camelize() ¶ protected
_camelize(string $name): string
Creates a camelized version of $name
Parameters
-
string
$name name
Returns
string
_checkPersistenceStatus() ¶ protected
_checkPersistenceStatus(Cake\ORM\Entity $sourceEntity, array $targetEntities): bool
Throws an exception should any of the passed entities is not persisted.
Parameters
-
Cake\ORM\Entity
$sourceEntity the row belonging to the
source
side of this association-
array
$targetEntities list of entities belonging to the
target
side of this association
Returns
bool
Throws
InvalidArgumentException
_collectJointEntities() ¶ protected
_collectJointEntities(Cake\Datasource\EntityInterface $sourceEntity, array $targetEntities): array
Returns the list of joint entities that exist between the source entity and each of the passed target entities
Parameters
-
Cake\Datasource\EntityInterface
$sourceEntity The row belonging to the source side of this association.
-
array
$targetEntities The rows belonging to the target side of this association.
Returns
array
Throws
InvalidArgumentException
if any of the entities is lacking a primary key value
_createTupleCondition() ¶ protected
_createTupleCondition(Cake\ORM\Query $query, array $keys, mixed $filter, string $operator): Cake\Database\Expression\TupleComparison
Returns a TupleComparison object that can be used for matching all the fields from $keys with the tuple values in $filter using the provided operator.
Parameters
-
Cake\ORM\Query
$query Target table's query
-
array
$keys the fields that should be used for filtering
-
mixed
$filter the value that should be used to match for $key
-
string
$operator The operator for comparing the tuples
Returns
Cake\Database\Expression\TupleComparison
_defaultOptions() ¶ protected
_defaultOptions(): array
Returns the default options to use for the eagerLoader
Returns
array
_diffLinks() ¶ protected
_diffLinks(Cake\ORM\Query $existing, array $jointEntities, array $targetEntities): array
Helper method used to delete the difference between the links passed in
$existing
and $jointEntities
. This method will return the values from
$targetEntities
that were not deleted from calculating the difference.
Parameters
-
Cake\ORM\Query
$existing a query for getting existing links
-
array
$jointEntities link entities that should be persisted
-
array
$targetEntities entities in target table that are related to the
$jointEntities
Returns
array
_dispatchBeforeFind() ¶ protected
_dispatchBeforeFind(Cake\ORM\Query $query): void
Triggers beforeFind on the target table for the query this association is attaching to
Parameters
-
Cake\ORM\Query
$query the query this association is attaching itself to
Returns
void
_entityName() ¶ protected
_entityName(string $name): string
Creates the proper entity name (singular) for the specified name
Parameters
-
string
$name Name
Returns
string
_extractFinder() ¶ protected
_extractFinder(string|array $finderData): array
Helper method to infer the requested finder and its options.
Returns the inferred options from the finder $type.
Examples:
The following will call the finder 'translations' with the value of the finder as its options: $query->contain(['Comments' => ['finder' => ['translations']]]); $query->contain(['Comments' => ['finder' => ['translations' => []]]]); $query->contain(['Comments' => ['finder' => ['translations' => ['locales' => ['en_US']]]]]);
Parameters
-
string|array
$finderData The finder name or an array having the name as key and options as value.
Returns
array
_fixtureName() ¶ protected
_fixtureName(string $name): string
Creates a fixture name
Parameters
-
string
$name Model class name
Returns
string
_formatAssociationResults() ¶ protected
_formatAssociationResults(Cake\ORM\Query $query, Cake\ORM\Query $surrogate, array $options): void
Adds a formatter function to the passed $query
if the $surrogate
query
declares any other formatter. Since the $surrogate
query correspond to
the associated target table, the resulting formatter will be the result of
applying the surrogate formatters to only the property corresponding to
such table.
Parameters
-
Cake\ORM\Query
$query the query that will get the formatter applied to
-
Cake\ORM\Query
$surrogate the query having formatters for the associated target table.
-
array
$options options passed to the method
attachTo
Returns
void
_joinCondition() ¶ protected
_joinCondition(array $options): bool
Return false as join conditions are defined in the junction table
Parameters
-
array
$options list of options passed to attachTo method
Returns
bool
_junctionAssociationName() ¶ protected
_junctionAssociationName(): string
Returns the name of the association from the target table to the junction table, this name is used to generate alias in the query and to later on retrieve the results.
Returns
string
_junctionTableName() ¶ protected
_junctionTableName(string|null $name = null): string
Sets the name of the junction table. If no arguments are passed the current configured name is returned. A default name based of the associated tables will be generated if none found.
Parameters
-
string|null
$name optional The name of the junction table.
Returns
string
_linkField() ¶ protected
_linkField(array $options): string
Generates a string used as a table field that contains the values upon which the filter should be applied
Parameters
-
array
$options the options to use for getting the link field.
Returns
string
_modelKey() ¶ protected
_modelKey(string $name): string
Creates the proper underscored model key for associations
If the input contains a dot, assume that the right side is the real table name.
Parameters
-
string
$name Model class name
Returns
string
_modelNameFromKey() ¶ protected
_modelNameFromKey(string $key): string
Creates the proper model name from a foreign key
Parameters
-
string
$key Foreign key
Returns
string
_multiKeysInjector() ¶ protected
_multiKeysInjector(array $resultMap, array $sourceKeys, string $nestKey): Closure
Returns a callable to be used for each row in a query result set for injecting the eager loaded rows when the matching needs to be done with multiple foreign keys
Parameters
-
array
$resultMap A keyed arrays containing the target table
-
array
$sourceKeys An array with aliased keys to match
-
string
$nestKey The key under which results should be nested
Returns
Closure
_options() ¶ protected
_options(array $opts): void
Parse extra options passed in the constructor.
Parameters
-
array
$opts original list of options passed in constructor
Returns
void
_pluginNamespace() ¶ protected
_pluginNamespace(string $pluginName): string
Return plugin's namespace
Parameters
-
string
$pluginName Plugin name
Returns
string
_pluginPath() ¶ protected
_pluginPath(string $pluginName): string
Find the correct path for a plugin. Scans $pluginPaths for the plugin you want.
Parameters
-
string
$pluginName Name of the plugin you want ie. DebugKit
Returns
string
_pluralHumanName() ¶ protected
_pluralHumanName(string $name): string
Creates the plural human name used in views
Parameters
-
string
$name Controller name
Returns
string
_resultInjector() ¶ protected
_resultInjector(Cake\ORM\Query $fetchQuery, array $resultMap, array $options): Closure
Returns a callable to be used for each row in a query result set for injecting the eager loaded rows
Parameters
-
Cake\ORM\Query
$fetchQuery the Query used to fetch results
-
array
$resultMap an array with the foreignKey as keys and the corresponding target table results as value.
-
array
$options The options passed to the eagerLoader method
Returns
Closure
_saveLinks() ¶ protected
_saveLinks(Cake\Datasource\EntityInterface $sourceEntity, array $targetEntities, array $options): bool
Creates links between the source entity and each of the passed target entities
Parameters
-
Cake\Datasource\EntityInterface
$sourceEntity the entity from source table in this association
-
array
$targetEntities list of entities to link to link to the source entity using the junction table
-
array
$options list of options accepted by Table::save()
Returns
bool
_saveTarget() ¶ protected
_saveTarget(Cake\Datasource\EntityInterface $parentEntity, arrayTraversable $entities, array $options): Cake\Datasource\EntityInterface|bool
Persists each of the entities into the target table and creates links between the parent entity and each one of the saved target entities.
Parameters
-
Cake\Datasource\EntityInterface
$parentEntity the source entity containing the target entities to be saved.
-
arrayTraversable
$entities list of entities to persist in target table and to link to the parent entity
-
array
$options list of options accepted by Table::save()
Returns
Cake\Datasource\EntityInterface|bool
Throws
InvalidArgumentException
if the property representing the association in the parent entity cannot be traversed
_singularHumanName() ¶ protected
_singularHumanName(string $name): string
Creates the singular human name used in views
Parameters
-
string
$name Controller name
Returns
string
_singularName() ¶ protected
_singularName(string $name): string
Creates the singular name for use in views.
Parameters
-
string
$name Name to use
Returns
string
_variableName() ¶ protected
_variableName(string $name): string
Creates the plural variable name for views
Parameters
-
string
$name Name to use
Returns
string
attachTo() ¶ public
attachTo(Query $query, array $options = []): void
Alters a Query object to include the associated target table data in the final result
The options array accept the following keys:
- includeFields: Whether to include target model fields in the result or not
- 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
- fields: a list of fields in the target table to include in the result
- type: The type of join to be used (e.g. INNER)
Parameters
-
Query
$query the query to be altered to include the target table data
-
array
$options optional Any extra options or overrides to be taken in account
Returns
void
bindingKey() ¶ public
bindingKey(string|null $key = null): string|array
Sets the name of the field representing the binding field with the target table. When not manually specified the primary key of the owning side table is used.
If no parameters are passed the current field is returned
Parameters
-
string|null
$key optional the table field to be used to link both tables together
Returns
string|array
canBeJoined() ¶ public
canBeJoined(array $options = []): bool
Whether this association can be expressed directly in a query join
Parameters
-
array
$options optional custom options key that could alter the return value
Returns
bool
cascadeCallbacks() ¶ public
cascadeCallbacks(bool|null $cascadeCallbacks = null): bool
Sets whether or not cascaded deletes should also fire callbacks. If no arguments are passed, the current configured value is returned
Parameters
-
bool|null
$cascadeCallbacks optional cascade callbacks switch value
Returns
bool
cascadeDelete() ¶ public
cascadeDelete(Cake\Datasource\EntityInterface $entity, array $options = []): bool
Clear out the data in the junction table for a given entity.
Each implementing class should handle the cascaded delete as required.
Parameters
-
Cake\Datasource\EntityInterface
$entity The entity that started the cascading delete.
-
array
$options optional The options for the original delete.
Returns
bool
conditions() ¶ public
conditions(array|null $conditions = null): array
Sets a list of conditions to be always included when fetching records from the target association. If no parameters are passed the current list is returned
Parameters
-
array|null
$conditions optional list of conditions to be used
Returns
array
See Also
defaultRowValue() ¶ public
defaultRowValue(array $row, bool $joined): array
Returns a modified row after appending a property for this association with the default empty value according to whether the association was joined or fetched externally.
Parameters
-
array
$row -
bool
$joined
Returns
array
deleteAll() ¶ public
deleteAll(mixed $conditions): bool
Proxies the delete operation to the target table's deleteAll method
Parameters
-
mixed
$conditions Conditions to be used, accepts anything Query::where() can take.
Returns
bool
See Also
dependent() ¶ public
dependent(bool|null $dependent = null): bool
Sets whether the records on the target table are dependent on the source table.
This is primarily used to indicate that records should be removed if the owning record in the source table is deleted.
If no parameters are passed the current setting is returned.
Parameters
-
bool|null
$dependent optional Set the dependent mode. Use null to read the current state.
Returns
bool
eagerLoader() ¶ public
eagerLoader(array $options): Closure
Eager loads a list of records in the target table that are related to another set of records in the source table. Source records can specified in two ways: first one is by passing a Query object setup to find on the source table and the other way is by explicitly passing an array of primary key values from the source table.
The required way of passing related source records is controlled by "strategy" When the subquery strategy is used it will require a query on the source table. When using the select strategy, the list of primary keys will be used.
Returns a closure that should be run for each record returned in a specific Query. This callable will be responsible for injecting the fields that are related to each specific passed row.
Options array accepts the following keys:
- query: Query object setup to find the source table records
- keys: List of primary key values from the source table
- foreignKey: The name of the field used to relate both tables
- conditions: List of conditions to be passed to the query where() method
- sort: The direction in which the records should be returned
- fields: List of fields to select from the target table
- contain: List of related tables to eager load associated to the target table
- strategy: The name of strategy to use for finding target table records
- nestKey: The array key under which results will be found when transforming the row
Parameters
-
array
$options
Returns
Closure
find() ¶ public
find(string|array $type = null, array $options = []): Cake\ORM\Query
Proxies the finding operation to the target table's find method and modifies the query accordingly based of this association configuration
Parameters
-
string|array
$type optional the type of query to perform, if an array is passed, it will be interpreted as the
$options
parameter-
array
$options optional The options to for the find
Returns
Cake\ORM\Query
See Also
finder() ¶ public
finder(string|null $finder = null): string
Sets the default finder to use for fetching rows from the target table. If no parameters are passed, it will return the currently configured finder name.
Parameters
-
string|null
$finder optional the finder name to use
Returns
string
foreignKey() ¶ public
foreignKey(string|null $key = null): string
Sets the name of the field representing the foreign key to the source table. If no parameters are passed current field is returned
Parameters
-
string|null
$key optional the key to be used to link both tables together
Returns
string
isOwningSide() ¶ public
isOwningSide(Cake\ORM\Table $side): bool
Returns boolean true, as both of the tables 'own' rows in the other side of the association via the joint table.
Parameters
-
Cake\ORM\Table
$side The potential Table with ownership
Returns
bool
joinType() ¶ public
joinType(string $type = null): string
Sets the type of join to be used when adding the association to a query. If no arguments are passed, the currently configured type is returned.
Parameters
-
string
$type optional the join type to be used (e.g. INNER)
Returns
string
junction() ¶ public
junction(stringCake\ORM\Table|null $table = null): Cake\ORM\Table
Sets the table instance for the junction relation. If no arguments are passed, the current configured table instance is returned
Parameters
-
stringCake\ORM\Table|null
$table optional Name or instance for the join table
Returns
Cake\ORM\Table
link() ¶ public
link(Cake\Datasource\EntityInterface $sourceEntity, array $targetEntities, array $options = []): bool
Associates the source entity to each of the target entities provided by creating links in the junction table. Both the source entity and each of the target entities are assumed to be already persisted, if the are marked as new or their status is unknown, an exception will be thrown.
When using this method, all entities in $targetEntities
will be appended to
the source entity's property corresponding to this association object.
This method does not check link uniqueness.
Example:
$newTags = $tags->find('relevant')->execute();
$articles->association('tags')->link($article, $newTags);
$article->get('tags')
will contain all tags in $newTags
after liking
Parameters
-
Cake\Datasource\EntityInterface
$sourceEntity the row belonging to the
source
side of this association-
array
$targetEntities list of entities belonging to the
target
side of this association-
array
$options optional list of options to be passed to the save method
Returns
bool
Throws
InvalidArgumentException
when any of the values in $targetEntities is detected to not be already persisted
name() ¶ public
name(string|null $name = null): string
Sets the name for this association. If no argument is passed then the current configured name will be returned
Parameters
-
string|null
$name optional Name to be assigned
Returns
string
property() ¶ public
property(string|null $name = null): string
Sets the property name that should be filled with data from the target table in the source table record. If no arguments are passed, the currently configured type is returned.
Parameters
-
string|null
$name optional The name of the association property. Use null to read the current value.
Returns
string
replaceLinks() ¶ public
replaceLinks(Cake\Datasource\EntityInterface $sourceEntity, array $targetEntities, array $options = []): bool
Replaces existing association links between the source entity and the target
with the ones passed. This method does a smart cleanup, links that are already
persisted and present in $targetEntities
will not be deleted, new links will
be created for the passed target entities that are not already in the database
and the rest will be removed.
For example, if an article is linked to tags 'cake' and 'framework' and you pass to this method an array containing the entities for tags 'cake', 'php' and 'awesome', only the link for cake will be kept in database, the link for 'framework' will be deleted and the links for 'php' and 'awesome' will be created.
Existing links are not deleted and created again, they are either left untouched or updated so that potential extra information stored in the joint row is not lost. Updating the link row can be done by making sure the corresponding passed target entity contains the joint property with its primary key and any extra information to be stored.
On success, the passed $sourceEntity
will contain $targetEntities
as value
in the corresponding property for this association.
This method assumes that links between both the source entity and each of the target entities are unique. That is, for any given row in the source table there can only be one link in the junction table pointing to any other given row in the target table.
Additional options for new links to be saved can be passed in the third argument,
check Table::save()
for information on the accepted options.
Example:
$article->tags = [$tag1, $tag2, $tag3, $tag4];
$articles->save($article);
$tags = [$tag1, $tag3];
$articles->association('tags')->replaceLinks($article, $tags);
$article->get('tags')
will contain only [$tag1, $tag3]
at the end
Parameters
-
Cake\Datasource\EntityInterface
$sourceEntity an entity persisted in the source table for this association
-
array
$targetEntities list of entities from the target table to be linked
-
array
$options optional list of options to be passed to
save
persisting or updating new links
Returns
bool
Throws
InvalidArgumentException
if non persisted entities are passed or if any of them is lacking a primary key value
requiresKeys() ¶ public
requiresKeys(array $options = []): bool
Returns true if the eager loading process will require a set of the owning table's binding keys in order to use them as a filter in the finder query.
Parameters
-
array
$options optional The options containing the strategy to be used.
Returns
bool
saveAssociated() ¶ public
saveAssociated(Cake\Datasource\EntityInterface $entity, arrayArrayObject $options = []): boolCake\Datasource\EntityInterface
Takes an entity from the source table and looks if there is a field
matching the property name for this association. The found entity will be
saved on the target table for this association by passing supplied
$options
When using the 'append' strategy, this function will only create new links between each side of this association. It will not destroy existing ones even though they may not be present in the array of entities to be saved.
When using the 'replace' strategy, existing links will be removed and new links will be created in the joint table. If there exists links in the database to some of the entities intended to be saved by this method, they will be updated, not deleted.
Parameters
-
Cake\Datasource\EntityInterface
$entity an entity from the source table
-
arrayArrayObject
$options optional options to be passed to the save method in the target table
Returns
boolCake\Datasource\EntityInterface
Throws
InvalidArgumentException
if the property representing the association in the parent entity cannot be traversed
See Also
BelongsToMany::replaceLinks()
saveStrategy() ¶ public
saveStrategy(string|null $strategy = null): string
Sets the strategy that should be used for saving. If called with no arguments, it will return the currently configured strategy
Parameters
-
string|null
$strategy optional the strategy name to be used
Returns
string
Throws
InvalidArgumentException
if an invalid strategy name is passed
sort() ¶ public
sort(mixed $sort = null): mixed
Sets the sort order in which target records should be returned. If no arguments are passed the currently configured value is returned
Parameters
-
mixed
$sort optional A find() compatible order clause
Returns
mixed
source() ¶ public
source(Cake\ORM\Table|null $table = null): Cake\ORM\Table
Sets the table instance for the source side of the association. If no arguments are passed, the current configured table instance is returned
Parameters
-
Cake\ORM\Table|null
$table optional the instance to be assigned as source side
Returns
Cake\ORM\Table
strategy() ¶ public
strategy(string|null $name = null): string
Sets the strategy name to be used to fetch associated records. Keep in mind that some association types might not implement but a default strategy, rendering any changes to this setting void. If no arguments are passed, the currently configured strategy is returned.
Parameters
-
string|null
$name optional The strategy type. Use null to read the current value.
Returns
string
Throws
InvalidArgumentException
When an invalid strategy is provided.
target() ¶ public
target(Cake\ORM\Table|null $table = null): Cake\ORM\Table
Sets the table instance for the target side of the association. If no arguments are passed, the current configured table instance is returned
Parameters
-
Cake\ORM\Table|null
$table optional the instance to be assigned as target side
Returns
Cake\ORM\Table
targetForeignKey() ¶ public
targetForeignKey(string|null $key = null): string
Sets the name of the field representing the foreign key to the target table. If no parameters are passed current field is returned
Parameters
-
string|null
$key optional the key to be used to link both tables together
Returns
string
transformRow() ¶ public
transformRow(array $row, string $nestKey, bool $joined): array
Correctly nests a result row associated values into the correct array keys inside the source results.
Parameters
-
array
$row -
string
$nestKey -
bool
$joined
Returns
array
unlink() ¶ public
unlink(Cake\Datasource\EntityInterface $sourceEntity, array $targetEntities, bool $cleanProperty = true): void
Removes all links between the passed source entity and each of the provided target entities. This method assumes that all passed objects are already persisted in the database and that each of them contain a primary key value.
By default this method will also unset each of the entity objects stored inside the source entity.
Example:
$article->tags = [$tag1, $tag2, $tag3, $tag4];
$tags = [$tag1, $tag2, $tag3];
$articles->association('tags')->unlink($article, $tags);
$article->get('tags')
will contain only [$tag4]
after deleting in the database
Parameters
-
Cake\Datasource\EntityInterface
$sourceEntity an entity persisted in the source table for this association
-
array
$targetEntities list of entities persisted in the target table for this association
-
bool
$cleanProperty optional whether or not to remove all the objects in $targetEntities that are stored in $sourceEntity
Returns
void
Throws
InvalidArgumentException
if non persisted entities are passed or if any of them is lacking a primary key value
updateAll() ¶ public
updateAll(array $fields, mixed $conditions): bool
Proxies the update operation to the target table's updateAll method
Parameters
-
array
$fields A hash of field => new value.
-
mixed
$conditions Conditions to be used, accepts anything Query::where() can take.
Returns
bool
See Also
Property Detail
$_bindingKey ¶ protected
The field name in the owning side table that is used to match with the foreignKey
Type
string|array
$_cascadeCallbacks ¶ protected
Whether or not cascaded deletes should also fire callbacks.
Type
string
$_conditions ¶ protected
A list of conditions to be always included when fetching records from the target association
Type
array
$_dependent ¶ protected
Whether the records on the joint table should be removed when a record on the source table is deleted.
Defaults to true for backwards compatibility.
Type
bool
$_finder ¶ protected
The default finder name to use for fetching rows from the target table
Type
string
$_foreignKey ¶ protected
The name of the field representing the foreign key to the table to load
Type
string|array
$_joinType ¶ protected
The type of join to be used when adding the association to a query
Type
string
$_junctionAssociationName ¶ protected
The name of the hasMany association from the target table to the junction table
Type
string
$_junctionProperty ¶ protected
The name of the property to be set containing data from the junction table once a record from the target table is hydrated
Type
string
$_name ¶ protected
Name given to the association, it usually represents the alias assigned to the target associated table
Type
string
$_propertyName ¶ protected
The property name that should be filled with data from the target table in the source table record.
Type
string
$_targetForeignKey ¶ protected
The name of the field representing the foreign key to the target table
Type
string|array