Fr3nch13/CakePHP Utilities

BelongsToMany extends Association
in package

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. In this example 'Article' is the source table and 'Tags' is the target table.

Table of Contents

Constants

MANY_TO_MANY  = 'manyToMany'
Association type for many to many associations.
MANY_TO_ONE  = 'manyToOne'
Association type for many to one associations.
ONE_TO_MANY  = 'oneToMany'
Association type for one to many associations.
ONE_TO_ONE  = 'oneToOne'
Association type for one to one associations.
SAVE_APPEND  = 'append'
Saving strategy that will only append to the links set
SAVE_REPLACE  = 'replace'
Saving strategy that will replace the links with the provided set
STRATEGY_JOIN  = 'join'
Strategy name to use joins for fetching associated records
STRATEGY_SELECT  = 'select'
Strategy name to use a select for fetching associated records
STRATEGY_SUBQUERY  = 'subquery'
Strategy name to use a subquery for fetching associated records

Properties

$_bindingKey  : array<string|int, string>|string|null
The field name in the owning side table that is used to match with the foreignKey
$_cascadeCallbacks  : bool
Whether cascaded deletes should also fire callbacks.
$_className  : string
The class name of the target table object
$_conditions  : Closure|array<string|int, mixed>
A list of conditions to be always included when fetching records from the target association
$_dependent  : bool
Whether the records on the joint table should be removed when a record on the source table is deleted.
$_finder  : array<string|int, mixed>|string
The default finder name to use for fetching rows from the target table With array value, finder name and default options are allowed.
$_foreignKey  : array<string|int, string>|string
The name of the field representing the foreign key to the table to load
$_joinType  : string
The type of join to be used when adding the association to a query
$_junctionAssociationName  : string
The name of the hasMany association from the target table to the junction table
$_junctionConditions  : array<string|int, mixed>|null
Filtered conditions that reference the junction table.
$_junctionProperty  : 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  : Table
Junction table instance
$_junctionTableName  : string
Junction table name
$_name  : string
Name given to the association, it usually represents the alias assigned to the target associated table
$_propertyName  : string
The property name that should be filled with data from the target table in the source table record.
$_saveStrategy  : string
Saving strategy to be used by this association
$_sort  : mixed
Order in which target records should be returned
$_sourceTable  : Table
Source table instance
$_strategy  : string
The strategy name to be used to fetch associated records.
$_tableLocator  : LocatorInterface|null
Table locator instance
$_targetConditions  : array<string|int, mixed>|null
Filtered conditions that reference the target table.
$_targetForeignKey  : array<string|int, string>|string|null
The name of the field representing the foreign key to the target table
$_targetTable  : Table
Target table instance
$_through  : Table|string
The table instance for the junction relation.
$_validStrategies  : array<string|int, string>
Valid strategies for this type of association
$defaultTable  : string|null
This object's default table alias.

Methods

__call()  : mixed
Proxies method calls to the target table.
__construct()  : mixed
Constructor. Subclasses can override _options function to get the original list of passed options if expecting any other special key
__get()  : Association
Proxies property retrieval to the target table. This is handy for getting this association's associations
__isset()  : 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
attachTo()  : void
Alters a Query object to include the associated target table data in the final result
canBeJoined()  : bool
Whether this association can be expressed directly in a query join
cascadeDelete()  : bool
Clear out the data in the junction table for a given entity.
defaultRowValue()  : array<string, mixed>
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()  : int
Proxies the delete operation to the target table's deleteAll method
eagerLoader()  : 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 be 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.
exists()  : bool
Proxies the operation to the target table's exists method after appending the default conditions for this association
fetchTable()  : Table
Convenience method to get a table instance.
find()  : Query
Proxies the finding operation to the target table's find method and modifies the query accordingly based of this association configuration.
getBindingKey()  : array<string|int, string>|string
Gets the name of the field representing the binding field with the target table.
getCascadeCallbacks()  : bool
Gets whether cascaded deletes should also fire callbacks.
getClassName()  : string
Gets the class name of the target table object.
getConditions()  : Closure|array<string|int, mixed>
Gets a list of conditions to be always included when fetching records from the target association.
getDependent()  : bool
Sets whether the records on the target table are dependent on the source table.
getFinder()  : array<string|int, mixed>|string
Gets the default finder to use for fetching rows from the target table.
getForeignKey()  : array<string|int, string>|string
Gets the name of the field representing the foreign key to the source table.
getJoinType()  : string
Gets the type of join to be used when adding the association to a query.
getName()  : string
Gets the name for this association, usually the alias assigned to the target associated table
getProperty()  : string
Gets the property name that should be filled with data from the target table in the source table record.
getSaveStrategy()  : string
Gets the strategy that should be used for saving.
getSort()  : mixed
Gets the sort order in which target records should be returned.
getSource()  : Table
Gets the table instance for the source side of the association.
getStrategy()  : string
Gets 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.
getTableLocator()  : LocatorInterface
Gets the table locator.
getTarget()  : Table
Gets the table instance for the target side of the association.
getTargetForeignKey()  : array<string|int, string>|string
Gets the name of the field representing the foreign key to the target table.
getThrough()  : Table|string
Gets the current join table, either the name of the Table instance or the instance itself.
isOwningSide()  : bool
Returns boolean true, as both of the tables 'own' rows in the other side of the association via the joint table.
junction()  : Table
Sets the table instance for the junction relation. If no arguments are passed, the current configured table instance is returned
link()  : 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 they are marked as new or their status is unknown then an exception will be thrown.
replaceLinks()  : 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.
requiresKeys()  : 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.
saveAssociated()  : EntityInterface|false
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`
setBindingKey()  : $this
Sets the name of the field representing the binding field with the target table.
setCascadeCallbacks()  : $this
Sets whether cascaded deletes should also fire callbacks.
setClassName()  : $this
Sets the class name of the target table object.
setConditions()  : $this
Sets a list of conditions to be always included when fetching records from the target association.
setDependent()  : $this
Sets whether the records on the target table are dependent on the source table.
setFinder()  : $this
Sets the default finder to use for fetching rows from the target table.
setForeignKey()  : $this
Sets the name of the field representing the foreign key to the target table.
setJoinType()  : $this
Sets the type of join to be used when adding the association to a query.
setName()  : $this
Sets the name for this association, usually the alias assigned to the target associated table
setProperty()  : $this
Sets the property name that should be filled with data from the target table in the source table record.
setSaveStrategy()  : $this
Sets the strategy that should be used for saving.
setSort()  : $this
Sets the sort order in which target records should be returned.
setSource()  : $this
Sets the table instance for the source side of the association.
setStrategy()  : $this
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.
setTableLocator()  : $this
Sets the table locator.
setTarget()  : $this
Sets the table instance for the target side of the association.
setTargetForeignKey()  : $this
Sets the name of the field representing the foreign key to the target table.
setThrough()  : $this
Sets the current join table, either the name of the Table instance or the instance itself.
transformRow()  : array<string|int, mixed>
Correctly nests a result row associated values into the correct array keys inside the source results.
type()  : string
Get the relationship type.
unlink()  : bool
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()  : int
Proxies the update operation to the target table's updateAll method
_appendFields()  : void
Helper function used to conditionally append fields to the select clause of a query from the fields found in another query object.
_appendJunctionJoin()  : Query
Append a join to the junction table.
_appendNotMatching()  : void
Conditionally adds a condition to the passed Query that will make it find records where there is no match with this association.
_bindNewAssociations()  : void
Applies all attachable associations to `$query` out of the containments found in the `$surrogate` query.
_camelize()  : string
Creates a camelized version of $name
_checkPersistenceStatus()  : bool
Throws an exception should any of the passed entities is not persisted.
_collectJointEntities()  : array<string|int, EntityInterface>
Returns the list of joint entities that exist between the source entity and each of the passed target entities
_diffLinks()  : array<string|int, mixed>|false
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()  : void
Triggers beforeFind on the target table for the query this association is attaching to
_entityName()  : string
Creates the proper entity name (singular) for the specified name
_extractFinder()  : array<string|int, mixed>
Helper method to infer the requested finder and its options.
_fixtureName()  : string
Creates a fixture name
_formatAssociationResults()  : 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.
_generateJunctionAssociations()  : void
Generate associations on the junction table as necessary
_generateSourceAssociations()  : void
Generate additional source table associations as necessary.
_generateTargetAssociations()  : void
Generate reciprocal associations as necessary.
_joinCondition()  : array<string|int, mixed>
Return false as join conditions are defined in the junction table
_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.
_junctionTableName()  : string
Sets the name of the junction table.
_modelKey()  : string
Creates the proper underscored model key for associations
_modelNameFromKey()  : string
Creates the proper model name from a foreign key
_options()  : void
Parse extra options passed in the constructor.
_pluginNamespace()  : string
Return plugin's namespace
_pluginPath()  : string
Find the correct path for a plugin. Scans $pluginPaths for the plugin you want.
_pluralHumanName()  : string
Creates the plural human name used in views
_propertyName()  : string
Returns default property name based on association name.
_saveLinks()  : bool
Creates links between the source entity and each of the passed target entities
_saveTarget()  : EntityInterface|false
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()  : string
Creates the singular human name used in views
_singularName()  : string
Creates the singular name for use in views.
_variableName()  : string
Creates the plural variable name for views
junctionConditions()  : array<string|int, mixed>
Returns filtered conditions that specifically reference the junction table.
targetConditions()  : array<string|int, mixed>|Closure|null
Returns filtered conditions that reference the target table.

Constants

MANY_TO_MANY

Association type for many to many associations.

public string MANY_TO_MANY = 'manyToMany'

MANY_TO_ONE

Association type for many to one associations.

public string MANY_TO_ONE = 'manyToOne'

ONE_TO_MANY

Association type for one to many associations.

public string ONE_TO_MANY = 'oneToMany'

ONE_TO_ONE

Association type for one to one associations.

public string ONE_TO_ONE = 'oneToOne'

SAVE_APPEND

Saving strategy that will only append to the links set

public string SAVE_APPEND = 'append'

SAVE_REPLACE

Saving strategy that will replace the links with the provided set

public string SAVE_REPLACE = 'replace'

STRATEGY_JOIN

Strategy name to use joins for fetching associated records

public string STRATEGY_JOIN = 'join'

STRATEGY_SELECT

Strategy name to use a select for fetching associated records

public string STRATEGY_SELECT = 'select'

STRATEGY_SUBQUERY

Strategy name to use a subquery for fetching associated records

public string STRATEGY_SUBQUERY = 'subquery'

Properties

$_bindingKey

The field name in the owning side table that is used to match with the foreignKey

protected array<string|int, string>|string|null $_bindingKey

$_cascadeCallbacks

Whether cascaded deletes should also fire callbacks.

protected bool $_cascadeCallbacks = false

$_className

The class name of the target table object

protected string $_className

$_conditions

A list of conditions to be always included when fetching records from the target association

protected Closure|array<string|int, mixed> $_conditions = []

$_dependent

Whether the records on the joint table should be removed when a record on the source table is deleted.

protected bool $_dependent = true

Defaults to true for backwards compatibility.

$_finder

The default finder name to use for fetching rows from the target table With array value, finder name and default options are allowed.

protected array<string|int, mixed>|string $_finder = 'all'

$_foreignKey

The name of the field representing the foreign key to the table to load

protected array<string|int, string>|string $_foreignKey

$_joinType

The type of join to be used when adding the association to a query

protected string $_joinType = \Cake\ORM\Query::JOIN_TYPE_INNER

$_junctionAssociationName

The name of the hasMany association from the target table to the junction table

protected string $_junctionAssociationName

$_junctionConditions

Filtered conditions that reference the junction table.

protected array<string|int, mixed>|null $_junctionConditions

$_junctionProperty

The name of the property to be set containing data from the junction table once a record from the target table is hydrated

protected string $_junctionProperty = '_joinData'

$_junctionTableName

Junction table name

protected string $_junctionTableName

$_name

Name given to the association, it usually represents the alias assigned to the target associated table

protected string $_name

$_propertyName

The property name that should be filled with data from the target table in the source table record.

protected string $_propertyName

$_saveStrategy

Saving strategy to be used by this association

protected string $_saveStrategy = self::SAVE_REPLACE

$_sort

Order in which target records should be returned

protected mixed $_sort

$_strategy

The strategy name to be used to fetch associated records.

protected string $_strategy = self::STRATEGY_SELECT

$_targetConditions

Filtered conditions that reference the target table.

protected array<string|int, mixed>|null $_targetConditions

$_targetForeignKey

The name of the field representing the foreign key to the target table

protected array<string|int, string>|string|null $_targetForeignKey

$_through

The table instance for the junction relation.

protected Table|string $_through

$_validStrategies

Valid strategies for this type of association

protected array<string|int, string> $_validStrategies = [self::STRATEGY_SELECT, self::STRATEGY_SUBQUERY]

$defaultTable

This object's default table alias.

protected string|null $defaultTable = null

Methods

__call()

Proxies method calls to the target table.

public __call(string $method, array<string|int, mixed> $argument) : mixed
Parameters
$method : string

name of the method to be invoked

$argument : array<string|int, mixed>

List of arguments passed to the function

Tags
throws
BadMethodCallException

__construct()

Constructor. Subclasses can override _options function to get the original list of passed options if expecting any other special key

public __construct(string $alias[, array<string, mixed> $options = [] ]) : mixed
Parameters
$alias : string

The name given to the association

$options : array<string, mixed> = []

A list of properties to be set on this object

__get()

Proxies property retrieval to the target table. This is handy for getting this association's associations

public __get(string $property) : Association
Parameters
$property : string

the property name

Tags
throws
RuntimeException

if no association with such name exists

Return values
Association

__isset()

Proxies the isset call to the target table. This is handy to check if the target table has another association with the passed name

public __isset(string $property) : bool
Parameters
$property : string

the property name

Return values
bool

true if the property exists

attachTo()

Alters a Query object to include the associated target table data in the final result

public attachTo(Query $query[, array<string, mixed> $options = [] ]) : void

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

$options : array<string, mixed> = []

Any extra options or overrides to be taken in account

canBeJoined()

Whether this association can be expressed directly in a query join

public canBeJoined([array<string, mixed> $options = [] ]) : bool
Parameters
$options : array<string, mixed> = []

custom options key that could alter the return value

Return values
bool

if the 'matching' key in $option is true then this function will return true, false otherwise

cascadeDelete()

Clear out the data in the junction table for a given entity.

public cascadeDelete(EntityInterface $entity[, array<string, mixed> $options = [] ]) : bool
Parameters
$entity : EntityInterface

The entity that started the cascading delete.

$options : array<string, mixed> = []

The options for the original delete.

Return values
bool

Success.

defaultRowValue()

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.

public defaultRowValue(array<string|int, mixed> $row, bool $joined) : array<string, mixed>
Parameters
$row : array<string|int, mixed>

The row to set a default on.

$joined : bool

Whether the row is a result of a direct join with this association

Tags
inheritDoc
Return values
array<string, mixed>

deleteAll()

Proxies the delete operation to the target table's deleteAll method

public deleteAll(ExpressionInterface|Closure|array<string|int, mixed>|string|null $conditions) : int
Parameters
$conditions : ExpressionInterface|Closure|array<string|int, mixed>|string|null

Conditions to be used, accepts anything Query::where() can take.

Tags
see
Table::deleteAll()
Return values
int

Returns the number of affected rows.

eagerLoader()

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 be 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.

public eagerLoader(array<string|int, mixed> $options) : Closure
Parameters
$options : array<string|int, mixed>

The options for eager loading.

Tags
inheritDoc
Return values
Closure

exists()

Proxies the operation to the target table's exists method after appending the default conditions for this association

public exists(ExpressionInterface|Closure|array<string|int, mixed>|string|null $conditions) : bool
Parameters
$conditions : ExpressionInterface|Closure|array<string|int, mixed>|string|null

The conditions to use for checking if any record matches.

Tags
see
Table::exists()
Return values
bool

fetchTable()

Convenience method to get a table instance.

public fetchTable([string|null $alias = null ][, array<string, mixed> $options = [] ]) : Table
Parameters
$alias : string|null = null

The alias name you want to get. Should be in CamelCase format. If null then the value of $defaultTable property is used.

$options : array<string, mixed> = []

The options you want to build the table with. If a table has already been loaded the registry options will be ignored.

Tags
throws
CakeException

If $alias argument and $defaultTable property both are null.

see
TableLocator::get()
since
4.3.0
Return values
Table

find()

Proxies the finding operation to the target table's find method and modifies the query accordingly based of this association configuration.

public find([array<string, mixed>|string|null $type = null ][, array<string, mixed> $options = [] ]) : Query

If your association includes conditions or a finder, the junction table will be included in the query's contained associations.

Parameters
$type : array<string, mixed>|string|null = null

the type of query to perform, if an array is passed, it will be interpreted as the $options parameter

$options : array<string, mixed> = []

The options to for the find

Tags
see
Table::find()
Return values
Query

getBindingKey()

Gets the name of the field representing the binding field with the target table.

public getBindingKey() : array<string|int, string>|string

When not manually specified the primary key of the owning side table is used.

Return values
array<string|int, string>|string

getCascadeCallbacks()

Gets whether cascaded deletes should also fire callbacks.

public getCascadeCallbacks() : bool
Return values
bool

getClassName()

Gets the class name of the target table object.

public getClassName() : string
Return values
string

getConditions()

Gets a list of conditions to be always included when fetching records from the target association.

public getConditions() : Closure|array<string|int, mixed>
Tags
see
Query::where()

for examples on the format of the array

Return values
Closure|array<string|int, mixed>

getDependent()

Sets whether the records on the target table are dependent on the source table.

public getDependent() : bool

This is primarily used to indicate that records should be removed if the owning record in the source table is deleted.

Return values
bool

getFinder()

Gets the default finder to use for fetching rows from the target table.

public getFinder() : array<string|int, mixed>|string
Return values
array<string|int, mixed>|string

getForeignKey()

Gets the name of the field representing the foreign key to the source table.

public getForeignKey() : array<string|int, string>|string
Return values
array<string|int, string>|string

getJoinType()

Gets the type of join to be used when adding the association to a query.

public getJoinType() : string
Return values
string

getName()

Gets the name for this association, usually the alias assigned to the target associated table

public getName() : string
Return values
string

getProperty()

Gets the property name that should be filled with data from the target table in the source table record.

public getProperty() : string
Return values
string

getSaveStrategy()

Gets the strategy that should be used for saving.

public getSaveStrategy() : string
Return values
string

the strategy to be used for saving

getSort()

Gets the sort order in which target records should be returned.

public getSort() : mixed

getSource()

Gets the table instance for the source side of the association.

public getSource() : Table
Return values
Table

getStrategy()

Gets 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.

public getStrategy() : string
Return values
string

getTarget()

Gets the table instance for the target side of the association.

public getTarget() : Table
Return values
Table

getTargetForeignKey()

Gets the name of the field representing the foreign key to the target table.

public getTargetForeignKey() : array<string|int, string>|string
Return values
array<string|int, string>|string

getThrough()

Gets the current join table, either the name of the Table instance or the instance itself.

public getThrough() : Table|string
Return values
Table|string

isOwningSide()

Returns boolean true, as both of the tables 'own' rows in the other side of the association via the joint table.

public isOwningSide(Table $side) : bool
Parameters
$side : Table

The potential Table with ownership

Return values
bool

junction()

Sets the table instance for the junction relation. If no arguments are passed, the current configured table instance is returned

public junction([Table|string|null $table = null ]) : Table
Parameters
$table : Table|string|null = null

Name or instance for the join table

Tags
throws
InvalidArgumentException

If the expected associations are incompatible with existing associations.

Return values
Table

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 they are marked as new or their status is unknown then an exception will be thrown.

public link(EntityInterface $sourceEntity, array<string|int, EntityInterface$targetEntities[, array<string, mixed> $options = [] ]) : bool

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')->toArray();
$articles->getAssociation('tags')->link($article, $newTags);

$article->get('tags') will contain all tags in $newTags after liking

Parameters
$sourceEntity : EntityInterface

the row belonging to the source side of this association

$targetEntities : array<string|int, EntityInterface>

list of entities belonging to the target side of this association

$options : array<string, mixed> = []

list of options to be passed to the internal save call

Tags
throws
InvalidArgumentException

when any of the values in $targetEntities is detected to not be already persisted

Return values
bool

true on success, false otherwise

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.

public replaceLinks(EntityInterface $sourceEntity, array<string|int, mixed> $targetEntities[, array<string, mixed> $options = [] ]) : bool

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->getAssociation('tags')->replaceLinks($article, $tags);

$article->get('tags') will contain only [$tag1, $tag3] at the end

Parameters
$sourceEntity : EntityInterface

an entity persisted in the source table for this association

$targetEntities : array<string|int, mixed>

list of entities from the target table to be linked

$options : array<string, mixed> = []

list of options to be passed to the internal save/delete calls when persisting/updating new links, or deleting existing ones

Tags
throws
InvalidArgumentException

if non persisted entities are passed or if any of them is lacking a primary key value

Return values
bool

success

requiresKeys()

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.

public requiresKeys([array<string, mixed> $options = [] ]) : bool
Parameters
$options : array<string, mixed> = []

The options containing the strategy to be used.

Return values
bool

true if a list of keys will be required

saveAssociated()

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`

public saveAssociated(EntityInterface $entity[, array<string, mixed> $options = [] ]) : EntityInterface|false

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
$entity : EntityInterface

an entity from the source table

$options : array<string, mixed> = []

options to be passed to the save method in the target table

Tags
throws
InvalidArgumentException

if the property representing the association in the parent entity cannot be traversed

see
Table::save()
see
BelongsToMany::replaceLinks()
Return values
EntityInterface|false

false if $entity could not be saved, otherwise it returns the saved entity

setBindingKey()

Sets the name of the field representing the binding field with the target table.

public setBindingKey(array<string|int, string>|string $key) : $this

When not manually specified the primary key of the owning side table is used.

Parameters
$key : array<string|int, string>|string

the table field or fields to be used to link both tables together

Return values
$this

setCascadeCallbacks()

Sets whether cascaded deletes should also fire callbacks.

public setCascadeCallbacks(bool $cascadeCallbacks) : $this
Parameters
$cascadeCallbacks : bool

cascade callbacks switch value

Return values
$this

setClassName()

Sets the class name of the target table object.

public setClassName(string $className) : $this
Parameters
$className : string

Class name to set.

Tags
throws
InvalidArgumentException

In case the class name is set after the target table has been resolved, and it doesn't match the target table's class name.

Return values
$this

setConditions()

Sets a list of conditions to be always included when fetching records from the target association.

public setConditions(mixed $conditions) : $this
Parameters
$conditions : mixed

list of conditions to be used

Tags
inheritDoc
Return values
$this

setDependent()

Sets whether the records on the target table are dependent on the source table.

public setDependent(bool $dependent) : $this

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
$dependent : bool

Set the dependent mode. Use null to read the current state.

Return values
$this

setFinder()

Sets the default finder to use for fetching rows from the target table.

public setFinder(array<string|int, mixed>|string $finder) : $this
Parameters
$finder : array<string|int, mixed>|string

the finder name to use or array of finder name and option.

Return values
$this

setForeignKey()

Sets the name of the field representing the foreign key to the target table.

public setForeignKey(array<string|int, string>|string $key) : $this
Parameters
$key : array<string|int, string>|string

the key or keys to be used to link both tables together

Return values
$this

setJoinType()

Sets the type of join to be used when adding the association to a query.

public setJoinType(string $type) : $this
Parameters
$type : string

the join type to be used (e.g. INNER)

Return values
$this

setName()

Sets the name for this association, usually the alias assigned to the target associated table

public setName(string $name) : $this

Changing the association name after object creation is no longer supported. The name should only be set through the constructor.

Parameters
$name : string

Name to be assigned

Return values
$this

setProperty()

Sets the property name that should be filled with data from the target table in the source table record.

public setProperty(string $name) : $this
Parameters
$name : string

The name of the association property. Use null to read the current value.

Return values
$this

setSaveStrategy()

Sets the strategy that should be used for saving.

public setSaveStrategy(string $strategy) : $this
Parameters
$strategy : string

the strategy name to be used

Tags
throws
InvalidArgumentException

if an invalid strategy name is passed

Return values
$this

setSort()

Sets the sort order in which target records should be returned.

public setSort(mixed $sort) : $this
Parameters
$sort : mixed

A find() compatible order clause

Return values
$this

setSource()

Sets the table instance for the source side of the association.

public setSource(Table $table) : $this
Parameters
$table : Table

the instance to be assigned as source side

Return values
$this

setStrategy()

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.

public setStrategy(string $name) : $this
Parameters
$name : string

The strategy type. Use null to read the current value.

Tags
throws
InvalidArgumentException

When an invalid strategy is provided.

Return values
$this

setTarget()

Sets the table instance for the target side of the association.

public setTarget(Table $table) : $this
Parameters
$table : Table

the instance to be assigned as target side

Return values
$this

setTargetForeignKey()

Sets the name of the field representing the foreign key to the target table.

public setTargetForeignKey(array<string|int, string>|string $key) : $this
Parameters
$key : array<string|int, string>|string

the key to be used to link both tables together

Return values
$this

setThrough()

Sets the current join table, either the name of the Table instance or the instance itself.

public setThrough(Table|string $through) : $this
Parameters
$through : Table|string

Name of the Table instance or the instance itself

Return values
$this

transformRow()

Correctly nests a result row associated values into the correct array keys inside the source results.

public transformRow(array<string|int, mixed> $row, string $nestKey, bool $joined[, string|null $targetProperty = null ]) : array<string|int, mixed>
Parameters
$row : array<string|int, mixed>

The row to transform

$nestKey : string

The array key under which the results for this association should be found

$joined : bool

Whether the row is a result of a direct join with this association

$targetProperty : string|null = null

The property name in the source results where the association data shuld be nested in. Will use the default one if not provided.

Return values
array<string|int, mixed>

type()

Get the relationship type.

public type() : string
Return values
string

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.

public unlink(EntityInterface $sourceEntity, array<string|int, EntityInterface$targetEntities[, array<string|int, string>|bool $options = [] ]) : bool

Options

Additionally to the default options accepted by Table::delete(), the following keys are supported:

  • cleanProperty: Whether to remove all the objects in $targetEntities that are stored in $sourceEntity (default: true)

By default this method will unset each of the entity objects stored inside the source entity.

Example:

$article->tags = [$tag1, $tag2, $tag3, $tag4];
$tags = [$tag1, $tag2, $tag3];
$articles->getAssociation('tags')->unlink($article, $tags);

$article->get('tags') will contain only [$tag4] after deleting in the database

Parameters
$sourceEntity : EntityInterface

An entity persisted in the source table for this association.

$targetEntities : array<string|int, EntityInterface>

List of entities persisted in the target table for this association.

$options : array<string|int, string>|bool = []

List of options to be passed to the internal delete call, or a boolean as cleanProperty key shortcut.

Tags
throws
InvalidArgumentException

If non persisted entities are passed or if any of them is lacking a primary key value.

Return values
bool

Success

updateAll()

Proxies the update operation to the target table's updateAll method

public updateAll(array<string|int, mixed> $fields, ExpressionInterface|Closure|array<string|int, mixed>|string|null $conditions) : int
Parameters
$fields : array<string|int, mixed>

A hash of field => new value.

$conditions : ExpressionInterface|Closure|array<string|int, mixed>|string|null

Conditions to be used, accepts anything Query::where() can take.

Tags
see
Table::updateAll()
Return values
int

Count Returns the affected rows.

_appendFields()

Helper function used to conditionally append fields to the select clause of a query from the fields found in another query object.

protected _appendFields(Query $query, Query $surrogate, array<string, mixed> $options) : void
Parameters
$query : Query

the query that will get the fields appended to

$surrogate : Query

the query having the fields to be copied from

$options : array<string, mixed>

options passed to the method attachTo

_appendJunctionJoin()

Append a join to the junction table.

protected _appendJunctionJoin(Query $query[, array<string|int, mixed>|null $conditions = null ]) : Query
Parameters
$query : Query

The query to append.

$conditions : array<string|int, mixed>|null = null

The query conditions to use.

Return values
Query

The modified query.

_appendNotMatching()

Conditionally adds a condition to the passed Query that will make it find records where there is no match with this association.

protected _appendNotMatching(Query $query, array<string|int, mixed> $options) : void
Parameters
$query : Query

The query to modify

$options : array<string|int, mixed>

Options array containing the negateMatch key.

Tags
inheritDoc

_bindNewAssociations()

Applies all attachable associations to `$query` out of the containments found in the `$surrogate` query.

protected _bindNewAssociations(Query $query, Query $surrogate, array<string, mixed> $options) : void

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
$query : Query

the query that will get the associations attached to

$surrogate : Query

the query having the containments to be attached

$options : array<string, mixed>

options passed to the method attachTo

_camelize()

Creates a camelized version of $name

protected _camelize(string $name) : string
Parameters
$name : string

name

Return values
string

Camelized name

_checkPersistenceStatus()

Throws an exception should any of the passed entities is not persisted.

protected _checkPersistenceStatus(EntityInterface $sourceEntity, array<string|int, EntityInterface$targetEntities) : bool
Parameters
$sourceEntity : EntityInterface

the row belonging to the source side of this association

$targetEntities : array<string|int, EntityInterface>

list of entities belonging to the target side of this association

Tags
throws
InvalidArgumentException
Return values
bool

_collectJointEntities()

Returns the list of joint entities that exist between the source entity and each of the passed target entities

protected _collectJointEntities(EntityInterface $sourceEntity, array<string|int, mixed> $targetEntities) : array<string|int, EntityInterface>
Parameters
$sourceEntity : EntityInterface

The row belonging to the source side of this association.

$targetEntities : array<string|int, mixed>

The rows belonging to the target side of this association.

Tags
throws
InvalidArgumentException

if any of the entities is lacking a primary key value

Return values
array<string|int, EntityInterface>

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.

protected _diffLinks(Query $existing, array<string|int, EntityInterface$jointEntities, array<string|int, mixed> $targetEntities[, array<string, mixed> $options = [] ]) : array<string|int, mixed>|false
Parameters
$existing : Query

a query for getting existing links

$jointEntities : array<string|int, EntityInterface>

link entities that should be persisted

$targetEntities : array<string|int, mixed>

entities in target table that are related to the $jointEntities

$options : array<string, mixed> = []

list of options accepted by Table::delete()

Return values
array<string|int, mixed>|false

Array of entities not deleted or false in case of deletion failure for atomic saves.

_dispatchBeforeFind()

Triggers beforeFind on the target table for the query this association is attaching to

protected _dispatchBeforeFind(Query $query) : void
Parameters
$query : Query

the query this association is attaching itself to

_entityName()

Creates the proper entity name (singular) for the specified name

protected _entityName(string $name) : string
Parameters
$name : string

Name

Return values
string

Camelized and plural model name

_extractFinder()

Helper method to infer the requested finder and its options.

protected _extractFinder(array<string|int, mixed>|string $finderData) : array<string|int, mixed>

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
$finderData : array<string|int, mixed>|string

The finder name or an array having the name as key and options as value.

Return values
array<string|int, mixed>

_fixtureName()

Creates a fixture name

protected _fixtureName(string $name) : string
Parameters
$name : string

Model class name

Return values
string

Singular model key

_formatAssociationResults()

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.

protected _formatAssociationResults(Query $query, Query $surrogate, array<string, mixed> $options) : void
Parameters
$query : Query

the query that will get the formatter applied to

$surrogate : Query

the query having formatters for the associated target table.

$options : array<string, mixed>

options passed to the method attachTo

_generateJunctionAssociations()

Generate associations on the junction table as necessary

protected _generateJunctionAssociations(Table $junction, Table $source, Table $target) : void

Generates the following associations:

  • junction belongsTo source e.g. ArticlesTags belongsTo Tags
  • junction belongsTo target e.g. ArticlesTags belongsTo Articles

You can override these generated associations by defining associations with the correct aliases.

Parameters
$junction : Table

The junction table.

$source : Table

The source table.

$target : Table

The target table.

Tags
throws
InvalidArgumentException

If the expected associations are incompatible with existing associations.

_generateSourceAssociations()

Generate additional source table associations as necessary.

protected _generateSourceAssociations(Table $junction, Table $source) : void

Generates the following associations:

  • source hasMany junction e.g. Tags hasMany ArticlesTags

You can override these generated associations by defining associations with the correct aliases.

Parameters
$junction : Table

The junction table.

$source : Table

The source table.

_generateTargetAssociations()

Generate reciprocal associations as necessary.

protected _generateTargetAssociations(Table $junction, Table $source, Table $target) : void

Generates the following associations:

  • target hasMany junction e.g. Articles hasMany ArticlesTags
  • target belongsToMany source e.g Articles belongsToMany Tags.

You can override these generated associations by defining associations with the correct aliases.

Parameters
$junction : Table

The junction table.

$source : Table

The source table.

$target : Table

The target table.

_joinCondition()

Return false as join conditions are defined in the junction table

protected _joinCondition(array<string, mixed> $options) : array<string|int, mixed>
Parameters
$options : array<string, mixed>

list of options passed to attachTo method

Return values
array<string|int, mixed>

_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.

protected _junctionAssociationName() : string
Return values
string

_junctionTableName()

Sets the name of the junction table.

protected _junctionTableName([string|null $name = null ]) : string

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
$name : string|null = null

The name of the junction table.

Return values
string

_modelKey()

Creates the proper underscored model key for associations

protected _modelKey(string $name) : string

If the input contains a dot, assume that the right side is the real table name.

Parameters
$name : string

Model class name

Return values
string

Singular model key

_modelNameFromKey()

Creates the proper model name from a foreign key

protected _modelNameFromKey(string $key) : string
Parameters
$key : string

Foreign key

Return values
string

Model name

_options()

Parse extra options passed in the constructor.

protected _options(array<string, mixed> $options) : void
Parameters
$options : array<string, mixed>

original list of options passed in constructor

_pluginNamespace()

Return plugin's namespace

protected _pluginNamespace(string $pluginName) : string
Parameters
$pluginName : string

Plugin name

Return values
string

Plugin's namespace

_pluginPath()

Find the correct path for a plugin. Scans $pluginPaths for the plugin you want.

protected _pluginPath(string $pluginName) : string
Parameters
$pluginName : string

Name of the plugin you want ie. DebugKit

Return values
string

path path to the correct plugin.

_pluralHumanName()

Creates the plural human name used in views

protected _pluralHumanName(string $name) : string
Parameters
$name : string

Controller name

Return values
string

Plural human name

_propertyName()

Returns default property name based on association name.

protected _propertyName() : string
Return values
string

Creates links between the source entity and each of the passed target entities

protected _saveLinks(EntityInterface $sourceEntity, array<string|int, EntityInterface$targetEntities, array<string, mixed> $options) : bool
Parameters
$sourceEntity : EntityInterface

the entity from source table in this association

$targetEntities : array<string|int, EntityInterface>

list of entities to link to link to the source entity using the junction table

$options : array<string, mixed>

list of options accepted by Table::save()

Return values
bool

success

_saveTarget()

Persists each of the entities into the target table and creates links between the parent entity and each one of the saved target entities.

protected _saveTarget(EntityInterface $parentEntity, array<string|int, mixed> $entities, array<string, mixed> $options) : EntityInterface|false
Parameters
$parentEntity : EntityInterface

the source entity containing the target entities to be saved.

$entities : array<string|int, mixed>

list of entities to persist in target table and to link to the parent entity

$options : array<string, mixed>

list of options accepted by Table::save()

Tags
throws
InvalidArgumentException

if the property representing the association in the parent entity cannot be traversed

Return values
EntityInterface|false

The parent entity after all links have been created if no errors happened, false otherwise

_singularHumanName()

Creates the singular human name used in views

protected _singularHumanName(string $name) : string
Parameters
$name : string

Controller name

Return values
string

Singular human name

_singularName()

Creates the singular name for use in views.

protected _singularName(string $name) : string
Parameters
$name : string

Name to use

Return values
string

Variable name

_variableName()

Creates the plural variable name for views

protected _variableName(string $name) : string
Parameters
$name : string

Name to use

Return values
string

Plural name for views

junctionConditions()

Returns filtered conditions that specifically reference the junction table.

protected junctionConditions() : array<string|int, mixed>
Return values
array<string|int, mixed>

targetConditions()

Returns filtered conditions that reference the target table.

protected targetConditions() : array<string|int, mixed>|Closure|null

Any string expressions, or expression objects will also be returned in this list.

Return values
array<string|int, mixed>|Closure|null

Generally an array. If the conditions are not an array, the association conditions will be returned unmodified.


        
On this page

Search results