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.
_appendJunctionJoin( Cake\ORM\Query $query , string|array $conditions )
Append a join to the junction table.
Cake\ORM\Query
$query
$conditions
Cake\ORM\Query
_appendNotMatching( Cake\Database\Query $query , array $options )
Conditionally adds a condition to the passed Query that will make it find records where there is no match with this association.
Cake\Database\Query
$query
$options
negateMatch
key.Cake\ORM\Association::_appendNotMatching()
_buildQuery( array $options )
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.
$options
Cake\ORM\Query
InvalidArgumentException
_buildResultMap( Cake\ORM\Query $fetchQuery , array $options )
Builds an array containing the results from fetchQuery indexed by the foreignKey value corresponding to this association.
Cake\ORM\Query
$fetchQuery
$options
array
RuntimeException
_checkPersistenceStatus( Cake\Datasource\EntityInterface $sourceEntity , array $targetEntities )
Throws an exception should any of the passed entities is not persisted.
Cake\Datasource\EntityInterface
$sourceEntity
source
side of this association$targetEntities
target
side of this associationboolean
InvalidArgumentException
_collectJointEntities( Cake\Datasource\EntityInterface $sourceEntity , array $targetEntities )
Returns the list of joint entities that exist between the source entity and each of the passed target entities
Cake\Datasource\EntityInterface
$sourceEntity
$targetEntities
array
InvalidArgumentException
_diffLinks( Cake\ORM\Query $existing , array $jointEntities , array $targetEntities , array $options [] )
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.
Cake\ORM\Query
$existing
$jointEntities
$targetEntities
$jointEntities
$options
optional [] Table::delete()
array
_generateJunctionAssociations( Cake\ORM\Table $junction , Cake\ORM\Table $source , Cake\ORM\Table $target )
Generate associations on the junction table as necessary
Generates the following associations:
You can override these generated associations by defining associations with the correct aliases.
Cake\ORM\Table
$junction
Cake\ORM\Table
$source
Cake\ORM\Table
$target
_generateSourceAssociations( Cake\ORM\Table $junction , Cake\ORM\Table $source )
Generate additional source table associations as necessary.
Generates the following associations:
You can override these generated associations by defining associations with the correct aliases.
Cake\ORM\Table
$junction
Cake\ORM\Table
$source
_generateTargetAssociations( Cake\ORM\Table $junction , Cake\ORM\Table $source , Cake\ORM\Table $target )
Generate reciprocal associations as necessary.
Generates the following associations:
You can override these generated associations by defining associations with the correct aliases.
Cake\ORM\Table
$junction
Cake\ORM\Table
$source
Cake\ORM\Table
$target
_joinCondition( array $options )
Return false as join conditions are defined in the junction table
$options
boolean
RuntimeException
Cake\ORM\Association::_joinCondition()
_junctionAssociationName( )
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.
string
_junctionTableName( string|null $name null )
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.
$name
optional null string
_linkField( array $options )
Generates a string used as a table field that contains the values upon which the filter should be applied
$options
string
_options( array $opts )
Parse extra options passed in the constructor.
$opts
Cake\ORM\Association::_options()
_saveLinks( Cake\Datasource\EntityInterface $sourceEntity , array $targetEntities , array $options )
Creates links between the source entity and each of the passed target entities
Cake\Datasource\EntityInterface
$sourceEntity
$targetEntities
$options
Table::save()
boolean
_saveTarget( Cake\Datasource\EntityInterface $parentEntity , array|Traversable $entities , array $options )
Persists each of the entities into the target table and creates links between the parent entity and each one of the saved target entities.
Cake\Datasource\EntityInterface
$parentEntity
$entities
$options
Table::save()
Cake\Datasource\EntityInterface|boolean
InvalidArgumentException
attachTo( Cake\ORM\Query $query , array $options [] )
Alters a Query object to include the associated target table data in the final result
The options array accept the following keys:
Cake\ORM\Query
$query
$options
optional [] RuntimeException
Cake\ORM\Association::attachTo()
cascadeDelete( Cake\Datasource\EntityInterface $entity , array $options [] )
Clear out the data in the junction table for a given entity.
Cake\Datasource\EntityInterface
$entity
$options
optional [] boolean
conditions( array|null $conditions null )
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
$conditions
optional null array
Cake\ORM\Association::conditions()
find( string|array $type null , array $options [] )
Proxies the finding operation to the target table's find method and modifies the query accordingly based of this association configuration.
If your association includes conditions, the junction table will be included in the query's contained associations.
$type
optional null $options
parameter$options
optional [] Cake\ORM\Query
Cake\ORM\Table::find()
Cake\ORM\Association::find()
isOwningSide( Cake\ORM\Table $side )
Returns boolean true, as both of the tables 'own' rows in the other side of the association via the joint table.
Cake\ORM\Table
$side
boolean
junction( string|Cake\ORM\Table|null $table null )
Sets the table instance for the junction relation. If no arguments are passed, the current configured table instance is returned
Cake\ORM\Table
|null $table
optional null Cake\ORM\Table
junctionConditions( )
Returns filtered conditions that specifically reference the junction table.
array
link( Cake\Datasource\EntityInterface $sourceEntity , array $targetEntities , array $options [] )
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.
$newTags = $tags->find('relevant')->execute(); $articles->association('tags')->link($article, $newTags);
$article->get('tags')
will contain all tags in $newTags
after liking
Cake\Datasource\EntityInterface
$sourceEntity
source
side of this association$targetEntities
target
side of this association$options
optional [] save
callboolean
InvalidArgumentException
replaceLinks( Cake\Datasource\EntityInterface $sourceEntity , array $targetEntities , array $options [] )
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.
$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
Cake\Datasource\EntityInterface
$sourceEntity
$targetEntities
$options
optional [] save
/delete
calls when persisting/updating new links, or deleting existing onesboolean
InvalidArgumentException
saveAssociated( Cake\Datasource\EntityInterface $entity , array $options [] )
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.
Cake\Datasource\EntityInterface
$entity
$options
optional [] boolean|Cake\Datasource\EntityInterface
InvalidArgumentException
Cake\ORM\Association\BelongsToMany::replaceLinks()
saveStrategy( string|null $strategy null )
Sets the strategy that should be used for saving. If called with no arguments, it will return the currently configured strategy
$strategy
optional null string
InvalidArgumentException
targetConditions( )
Returns filtered conditions that reference the target table.
Any string expressions, or expression objects will also be returned in this list.
mixed
targetForeignKey( string|null $key null )
Sets the name of the field representing the foreign key to the target table. If no parameters are passed current field is returned
$key
optional null string
transformRow( array $row , string $nestKey , boolean $joined )
Correctly nests a result row associated values into the correct array keys inside the source results.
$row
$nestKey
$joined
array
Cake\ORM\Association::transformRow()
unlink( Cake\Datasource\EntityInterface $sourceEntity , array $targetEntities , array|boolean $options [] )
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.
Additionally to the default options accepted by Table::delete()
, the following keys are supported:
$targetEntities
thatare stored in $sourceEntity
(default: true)
By default this method will unset each of the entity objects stored inside the source entity.
$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
Cake\Datasource\EntityInterface
$sourceEntity
$targetEntities
$options
optional [] delete
call, or a boolean
InvalidArgumentException
__call( string $method , array $argument )
Proxies method calls to the target table.
$method
$argument
mixed
BadMethodCallException
__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
$alias
$options
optional [] __get( string $property )
Proxies property retrieval to the target table. This is handy for getting this association's associations
$property
Cake\ORM\Association
RuntimeException
__isset( string $property )
Proxies the isset call to the target table. This is handy to check if the target table has another association with the passed name
$property
boolean
_appendFields( Cake\ORM\Query $query , Cake\ORM\Query $surrogate , array $options )
Helper function used to conditionally append fields to the select clause of a query from the fields found in another query object.
Cake\ORM\Query
$query
Cake\ORM\Query
$surrogate
$options
attachTo
_bindNewAssociations( Cake\ORM\Query $query , Cake\ORM\Query $surrogate , array $options )
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.
Cake\ORM\Query
$query
Cake\ORM\Query
$surrogate
$options
attachTo
_dispatchBeforeFind( Cake\ORM\Query $query )
Triggers beforeFind on the target table for the query this association is attaching to
Cake\ORM\Query
$query
_extractFinder( string|array $finderData )
Helper method to infer the requested finder and its options.
Returns the inferred options from the finder $type.
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']]]]]);
$finderData
array
_formatAssociationResults( Cake\ORM\Query $query , Cake\ORM\Query $surrogate , array $options )
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.
Cake\ORM\Query
$query
Cake\ORM\Query
$surrogate
$options
attachTo
bindingKey( string|null $key null )
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
$key
optional null string|array
canBeJoined( array $options [] )
Whether this association can be expressed directly in a query join
$options
optional [] boolean
cascadeCallbacks( boolean|null $cascadeCallbacks null )
Sets whether or not cascaded deletes should also fire callbacks. If no arguments are passed, the current configured value is returned
$cascadeCallbacks
optional null boolean
defaultRowValue( array $row , boolean $joined )
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.
$row
$joined
array
deleteAll( mixed $conditions )
Proxies the delete operation to the target table's deleteAll method
$conditions
boolean
Cake\ORM\Table::deleteAll()
dependent( boolean|null $dependent null )
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.
$dependent
optional null boolean
eagerLoader( array $options )
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:
$options
Closure
finder( string|null $finder null )
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.
$finder
optional null string
foreignKey( string|null $key null )
Sets the name of the field representing the foreign key to the target table. If no parameters are passed the current field is returned
$key
optional null string|array
joinType( string $type null )
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.
$type
optional null string
name( string|null $name null )
Sets the name for this association. If no argument is passed then the current configured name will be returned
$name
optional null string
property( string|null $name null )
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.
$name
optional null string
source( Cake\ORM\Table $table null )
Sets the table instance for the source side of the association. If no arguments are passed, the current configured table instance is returned
Cake\ORM\Table
$table
optional null Cake\ORM\Table
strategy( string|null $name null )
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.
$name
optional null string
InvalidArgumentException
target( Cake\ORM\Table $table null )
Sets the table instance for the target side of the association. If no arguments are passed, the current configured table instance is returned
Cake\ORM\Table
$table
optional null Cake\ORM\Table
updateAll( array $fields , mixed $conditions )
Proxies the update operation to the target table's updateAll method
$fields
$conditions
boolean
Cake\ORM\Table::updateAll()
_defaultOptions( )
Returns the default options to use for the eagerLoader
array
_externalOptions( array $opts )
Parse extra options passed in the constructor.
$opts
canBeJoined( array $options [] )
Whether this association can be expressed directly in a query join
$options
optional [] boolean
Cake\ORM\Association::canBeJoined()
defaultRowValue( mixed $row , mixed $joined )
Cake\ORM\Association::defaultRowValue()
foreignKey( string|null $key null )
Sets the name of the field representing the foreign key to the source table. If no parameters are passed current field is returned
$key
optional null string
Cake\ORM\Association::foreignKey()
sort( mixed $sort null )
Sets the sort order in which target records should be returned. If no arguments are passed the currently configured value is returned
$sort
optional null mixed
_addFilteringCondition( Cake\ORM\Query $query , string|array $key , mixed $filter )
Appends any conditions required to load the relevant set of records in the target table query given a filter key and some filtering values.
Cake\ORM\Query
$query
$key
$filter
Cake\ORM\Query
_addFilteringJoin( Cake\ORM\Query $query , string $key , Cake\ORM\Query $subquery )
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.
Cake\ORM\Query
$query
$key
Cake\ORM\Query
$subquery
Cake\ORM\Query
_buildBaseQuery( array $options )
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
$options
Cake\ORM\Query
InvalidArgumentException
_buildSubquery( Cake\ORM\Query $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.
Cake\ORM\Query
$query
Cake\ORM\Query
_createTupleCondition( Cake\ORM\Query $query , array $keys , mixed $filter , string $operator )
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.
Cake\ORM\Query
$query
$keys
$filter
$operator
Cake\Database\Expression\TupleComparison
_multiKeysInjector( array $resultMap , array $sourceKeys , string $nestKey )
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
$resultMap
$sourceKeys
$nestKey
Closure
_resultInjector( Cake\ORM\Query $fetchQuery , array $resultMap , array $options )
Returns a callable to be used for each row in a query result set for injecting the eager loaded rows
Cake\ORM\Query
$fetchQuery
$resultMap
$options
Closure
_subqueryFields( Cake\ORM\Query $query )
Calculate the fields that need to participate in a subquery.
Normally this includes the binding key columns. If there is a an ORDER BY, those columns are also included as the fields may be calculated or constant values, that need to be present to ensure the correct association data is loaded.
Cake\ORM\Query
$query
array
eagerLoader( array $options )
requiresKeys( array $options [] )
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.
$options
optional [] boolean
_camelize( string $name )
Creates a camelized version of $name
$name
string
_entityName( string $name )
Creates the proper entity name (singular) for the specified name
$name
string
_fixtureName( string $name )
Creates a fixture name
$name
string
_modelKey( string $name )
Creates the proper underscored model key for associations
If the input contains a dot, assume that the right side is the real table name.
$name
string
_modelNameFromKey( string $key )
Creates the proper model name from a foreign key
$key
string
_pluginNamespace( string $pluginName )
Return plugin's namespace
$pluginName
string
_pluginPath( string $pluginName )
Find the correct path for a plugin. Scans $pluginPaths for the plugin you want.
$pluginName
string
_pluralHumanName( string $name )
Creates the plural human name used in views
$name
string
_singularHumanName( string $name )
Creates the singular human name used in views
$name
string
_singularName( string $name )
Creates the singular name for use in views.
$name
string
_variableName( string $name )
Creates the plural variable name for views
$name
string
tableLocator( Cake\ORM\Locator\LocatorInterface $tableLocator null )
Sets the table locator. If no parameters are passed, it will return the currently used locator.
Cake\ORM\Locator\LocatorInterface
$tableLocator
optional null Cake\ORM\Locator\LocatorInterface
string | SAVE_APPEND Saving strategy that will only append to the links set | 'append' |
string | SAVE_REPLACE Saving strategy that will replace the links with the provided set | 'replace' |
MANY_TO_MANY, MANY_TO_ONE, ONE_TO_MANY, ONE_TO_ONE, STRATEGY_JOIN, STRATEGY_SELECT, STRATEGY_SUBQUERY |
protected string|array
The field name in the owning side table that is used to match with the foreignKey
protected string
Whether or not cascaded deletes should also fire callbacks.
false
protected array
A list of conditions to be always included when fetching records from the target association
[]
protected string
The default finder name to use for fetching rows from the target table
'all'
protected string|array
The name of the field representing the foreign key to the table to load
protected string
Name given to the association, it usually represents the alias assigned to the target associated table
protected string
The property name that should be filled with data from the target table in the source table record.
© 2005–2016 The Cake Software Foundation, Inc.
Licensed under the MIT License.
CakePHP is a registered trademark of Cake Software Foundation, Inc.
We are not endorsed by or affiliated with CakePHP.
http://api.cakephp.org/3.1/class-Cake.ORM.Association.BelongsToMany.html