CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Team
    • Issues (Github)
    • YouTube Channel
    • Get Involved
    • Bakery
    • Featured Resources
    • Newsletter
    • Certification
    • My CakePHP
    • CakeFest
    • Facebook
    • Twitter
    • Help & Support
    • Forum
    • Stack Overflow
    • IRC
    • Slack
    • Paid Support
CakePHP

C CakePHP 3.8 Red Velvet API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 3.8
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

Namespaces

  • Cake
    • Auth
      • Storage
    • Cache
      • Engine
    • Collection
      • Iterator
    • Command
    • Console
      • Exception
    • Controller
      • Component
      • Exception
    • Core
      • Configure
        • Engine
      • Exception
      • Retry
    • Database
      • Driver
      • Exception
      • Expression
      • Schema
      • Statement
      • Type
    • Datasource
      • Exception
    • Error
      • Middleware
    • Event
      • Decorator
    • Filesystem
    • Form
    • Http
      • Client
        • Adapter
        • Auth
      • Cookie
      • Exception
      • Middleware
      • Session
    • I18n
      • Formatter
      • Middleware
      • Parser
    • Log
      • Engine
    • Mailer
      • Exception
      • Transport
    • Network
      • Exception
    • ORM
      • Association
      • Behavior
        • Translate
      • Exception
      • Locator
      • Rule
    • Routing
      • Exception
      • Filter
      • Middleware
      • Route
    • Shell
      • Helper
      • Task
    • TestSuite
      • Fixture
      • Stub
    • Utility
      • Exception
    • Validation
    • View
      • Exception
      • Form
      • Helper
      • Widget
  • None

Classes

  • BelongsTo
  • BelongsToMany
  • HasMany
  • HasOne

Traits

  • DependentDeleteTrait

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.

Cake\ORM\Association uses Cake\Core\ConventionsTrait , Cake\ORM\Locator\LocatorAwareTrait
Extended by Cake\ORM\Association\BelongsToMany
Namespace: Cake\ORM\Association
Location: ORM/Association/BelongsToMany.php

Constants summary

  • string
    SAVE_APPEND ¶
    'append'
  • string
    SAVE_REPLACE ¶
    'replace'

Inherited Constants

  • MANY_TO_MANY, MANY_TO_ONE, ONE_TO_MANY, ONE_TO_ONE, STRATEGY_JOIN, STRATEGY_SELECT, STRATEGY_SUBQUERY

Properties summary

  • $_dependent protected
    boolean

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

  • $_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

  • $_junctionConditions protected
    array|null
    Filtered conditions that reference 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
  • $_saveStrategy protected
    string
    Saving strategy to be used by this association
  • $_sort protected
    mixed
    Order in which target records should be returned
  • $_strategy protected
    string
    The strategy name to be used to fetch associated records.
  • $_targetConditions protected
    array|null
    Filtered conditions that reference the target table.
  • $_targetForeignKey protected
    string|string[]
    The name of the field representing the foreign key to the target table
  • $_through protected
    string|Cake\ORM\Table
    The table instance for the junction relation.
  • $_validStrategies protected
    array
    Valid strategies for this type of association

Inherited Properties

  • _bindingKey, _cascadeCallbacks, _className, _conditions, _finder, _foreignKey, _name, _propertyName, _sourceTable, _targetTable _tableLocator

Method Summary

  • _appendJunctionJoin() protected
    Append a join to the junction table.
  • _appendNotMatching() protected

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

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

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

  • _generateJunctionAssociations() protected
    Generate associations on the junction table as necessary
  • _generateSourceAssociations() protected
    Generate additional source table associations as necessary.
  • _generateTargetAssociations() protected
    Generate reciprocal associations as necessary.
  • _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.

  • _options() protected
    Parse extra options passed in the constructor.
  • _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.

  • attachTo() public

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

  • canBeJoined() public
    Whether this association can be expressed directly in a query join
  • cascadeDelete() public
    Clear out the data in the junction table for a given entity.
  • 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.

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

  • getForeignKey() public
    Gets the name of the field representing the foreign key to the source table.
  • getSaveStrategy() public
    Gets the strategy that should be used for saving.
  • getSort() public
    Gets the sort order in which target records should be returned.
  • getTargetForeignKey() public
    Gets the name of the field representing the foreign key to the target table.
  • getThrough() public
    Gets the current join table, either the name of the Table instance or the instance itself.
  • isOwningSide() public

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

  • junction() public

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

  • junctionConditions() protected

    Returns filtered conditions that specifically reference the junction table.

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

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

  • 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 deprecated

    Sets the strategy that should be used for saving. If called with no arguments, it will return the currently configured strategy

  • setConditions() public

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

  • setSaveStrategy() public
    Sets the strategy that should be used for saving.
  • setSort() public
    Sets the sort order in which target records should be returned.
  • setTargetForeignKey() public
    Sets the name of the field representing the foreign key to the target table.
  • setThrough() public
    Sets the current join table, either the name of the Table instance or the instance itself.
  • sort() public deprecated

    Sets the sort order in which target records should be returned. If no arguments are passed the currently configured value is returned

  • targetConditions() protected
    Returns filtered conditions that reference the target table.
  • targetForeignKey() public deprecated

    Sets the name of the field representing the foreign key to the target table. If no parameters are passed current field is returned

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

Method Detail

_appendJunctionJoin() protected ¶

_appendJunctionJoin( Cake\ORM\Query $query , string|array $conditions )

Append a join to the junction table.

Parameters
Cake\ORM\Query $query
The query to append.
string|array $conditions
The query conditions to use.
Returns
Cake\ORM\Query
The modified query.

_appendNotMatching() protected ¶

_appendNotMatching( Cake\Datasource\QueryInterface $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.

Parameters
Cake\Datasource\QueryInterface $query
The query to modify
array $options
Options array containing the negateMatch key.
Overrides
Cake\ORM\Association::_appendNotMatching()

_checkPersistenceStatus() protected ¶

_checkPersistenceStatus( Cake\Datasource\EntityInterface $sourceEntity , array $targetEntities )

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

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

Returns
boolean
Throws
InvalidArgumentException

_collectJointEntities() protected ¶

_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

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
Cake\Datasource\EntityInterface[]
Throws
InvalidArgumentException

if any of the entities is lacking a primary key value


_diffLinks() protected ¶

_diffLinks( Cake\ORM\Query $existing , Cake\Datasource\EntityInterface[] $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.

Parameters
Cake\ORM\Query $existing
a query for getting existing links
Cake\Datasource\EntityInterface[] $jointEntities
link entities that should be persisted
array $targetEntities

entities in target table that are related to the $jointEntities

array $options optional []
list of options accepted by Table::delete()
Returns
array

_generateJunctionAssociations() protected ¶

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

  • 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
Cake\ORM\Table $junction
The junction table.
Cake\ORM\Table $source
The source table.
Cake\ORM\Table $target
The target table.

_generateSourceAssociations() protected ¶

_generateSourceAssociations( Cake\ORM\Table $junction , Cake\ORM\Table $source )

Generate additional source table associations as necessary.

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
Cake\ORM\Table $junction
The junction table.
Cake\ORM\Table $source
The source table.

_generateTargetAssociations() protected ¶

_generateTargetAssociations( Cake\ORM\Table $junction , Cake\ORM\Table $source , Cake\ORM\Table $target )

Generate reciprocal associations as necessary.

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
Cake\ORM\Table $junction
The junction table.
Cake\ORM\Table $source
The source table.
Cake\ORM\Table $target
The target table.

_joinCondition() protected ¶

_joinCondition( array $options )

Return false as join conditions are defined in the junction table

Parameters
array $options
list of options passed to attachTo method
Returns
boolean
false
Throws
RuntimeException

if the number of columns in the foreignKey do not match the number of columns in the source table primaryKey


Overrides
Cake\ORM\Association::_joinCondition()

_junctionAssociationName() protected ¶

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

Returns
string

_junctionTableName() protected ¶

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

Parameters
string|null $name optional null
The name of the junction table.
Returns
string

_options() protected ¶

_options( array $opts )

Parse extra options passed in the constructor.

Parameters
array $opts
original list of options passed in constructor
Overrides
Cake\ORM\Association::_options()

_saveLinks() protected ¶

_saveLinks( Cake\Datasource\EntityInterface $sourceEntity , Cake\Datasource\EntityInterface[] $targetEntities , array $options )

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

Cake\Datasource\EntityInterface[] $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
boolean
success

_saveTarget() protected ¶

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

Parameters
Cake\Datasource\EntityInterface $parentEntity

the source entity containing the target entities to be saved.

array|Traversable $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|boolean

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


Throws
InvalidArgumentException

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


attachTo() public ¶

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:

  • 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
Cake\ORM\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
Throws
RuntimeException

if the query builder passed does not return a query object


Overrides
Cake\ORM\Association::attachTo()

canBeJoined() public ¶

canBeJoined( array $options = [] )

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
boolean

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


Overrides
Cake\ORM\Association::canBeJoined()

cascadeDelete() public ¶

cascadeDelete( Cake\Datasource\EntityInterface $entity , array $options = [] )

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

Parameters
Cake\Datasource\EntityInterface $entity
The entity that started the cascading delete.
array $options optional []
The options for the original delete.
Returns
boolean
Success.

defaultRowValue() public ¶

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.

Parameters
array $row
The row to set a default on.
boolean $joined

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

Returns
array
Overrides
Cake\ORM\Association::defaultRowValue()

eagerLoader() public ¶

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.

Parameters
array $options
The options for eager loading.
Returns
Closure

find() public ¶

find( string|array|null $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.

Parameters
string|array|null $type optional null

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
\Cake\ORM\Table::find()
Overrides
Cake\ORM\Association::find()

getForeignKey() public ¶

getForeignKey( )

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

Returns
string
Overrides
Cake\ORM\Association::getForeignKey()

getSaveStrategy() public ¶

getSaveStrategy( )

Gets the strategy that should be used for saving.

Returns
string
the strategy to be used for saving

getSort() public ¶

getSort( )

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

Returns
mixed

getTargetForeignKey() public ¶

getTargetForeignKey( )

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

Returns
string|string[]

getThrough() public ¶

getThrough( )

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

Returns
string|Cake\ORM\Table

isOwningSide() public ¶

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.

Parameters
Cake\ORM\Table $side
The potential Table with ownership
Returns
boolean

junction() public ¶

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

Parameters
string|Cake\ORM\Table|null $table optional null
Name or instance for the join table
Returns
Cake\ORM\Table

junctionConditions() protected ¶

junctionConditions( )

Returns filtered conditions that specifically reference the junction table.

Returns
array

link() public ¶

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 they are marked as new or their status is unknown then 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')->toArray();
$articles->getAssociation('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 internal save call
Returns
boolean
true on success, false otherwise
Throws
InvalidArgumentException

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


replaceLinks() public ¶

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.

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
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 the internal save/delete calls when persisting/updating new links, or deleting existing ones

Returns
boolean
success
Throws
InvalidArgumentException

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


saveAssociated() public ¶

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.

Parameters
Cake\Datasource\EntityInterface $entity
an entity from the source table
array $options optional []
options to be passed to the save method in the target table
Returns
boolean|Cake\Datasource\EntityInterface

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


Throws
InvalidArgumentException

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


See
\Cake\ORM\Table::save()
\Cake\ORM\Association\BelongsToMany::replaceLinks()

saveStrategy() public deprecated ¶

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

Deprecated
3.4.0 Use setSaveStrategy()/getSaveStrategy() instead.
Parameters
string|null $strategy optional null
the strategy name to be used
Returns
string
the strategy to be used for saving
Throws
InvalidArgumentException
if an invalid strategy name is passed

setConditions() public ¶

setConditions( array|callable $conditions )

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

Parameters
array|callable $conditions
list of conditions to be used
Returns

$this
Overrides
Cake\ORM\Association::setConditions()

setSaveStrategy() public ¶

setSaveStrategy( string $strategy )

Sets the strategy that should be used for saving.

Parameters
string $strategy
the strategy name to be used
Returns

$this
Throws
InvalidArgumentException
if an invalid strategy name is passed

setSort() public ¶

setSort( mixed $sort )

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

Parameters
mixed $sort
A find() compatible order clause
Returns

$this

setTargetForeignKey() public ¶

setTargetForeignKey( string|string[] $key )

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

Parameters
string|string[] $key
the key to be used to link both tables together
Returns

$this

setThrough() public ¶

setThrough( string|Cake\ORM\Table $through )

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

Parameters
string|Cake\ORM\Table $through
Name of the Table instance or the instance itself
Returns

$this

sort() public deprecated ¶

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

Deprecated
3.5.0 Use setSort()/getSort() instead.
Parameters
mixed $sort optional null
A find() compatible order clause
Returns
mixed

targetConditions() protected ¶

targetConditions( )

Returns filtered conditions that reference the target table.

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

Returns
mixed

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


targetForeignKey() public deprecated ¶

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

Deprecated
3.4.0 Use setTargetForeignKey()/getTargetForeignKey() instead.
Parameters
string|null $key optional null
the key to be used to link both tables together
Returns
string

type() public ¶

type( )

Get the relationship type.

Returns
string

unlink() public ¶

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.

Options

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

  • cleanProperty: Whether or not 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
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.

array|boolean $options optional []

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

Returns
boolean
Success
Throws
InvalidArgumentException

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


Methods inherited from Cake\ORM\Association

__call() public ¶

__call( string $method , array $argument )

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 )

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 )

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
boolean
true if the property exists

_appendFields() protected ¶

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

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

_bindNewAssociations() protected ¶

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

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

_dispatchBeforeFind() protected ¶

_dispatchBeforeFind( Cake\ORM\Query $query )

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

_extractFinder() protected ¶

_extractFinder( string|array $finderData )

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

_formatAssociationResults() protected ¶

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

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

_getClassName() protected ¶

_getClassName( string $alias , array $options = [] )

Gets the table class name.

Parameters
string $alias
The alias name you want to get.
array $options optional []
Table options array.
Returns
string

_propertyName() protected ¶

_propertyName( )

Returns default property name based on association name.

Returns
string

bindingKey() public deprecated ¶

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

Deprecated
3.4.0 Use setBindingKey()/getBindingKey() instead.
Parameters
string|null $key optional null
the table field to be used to link both tables together
Returns
string|array

cascadeCallbacks() public deprecated ¶

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

Deprecated
3.4.0 Use setCascadeCallbacks()/getCascadeCallbacks() instead.
Parameters
boolean|null $cascadeCallbacks optional null
cascade callbacks switch value
Returns
boolean

className() public deprecated ¶

className( )

The class name of the target table object

Deprecated
3.7.0 Use getClassName() instead.
Returns
string

conditions() public deprecated ¶

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

Deprecated
3.4.0 Use setConditions()/getConditions() instead.
Parameters
array|null $conditions optional null
list of conditions to be used
Returns
array|callable
See
\Cake\Database\Query::where() for examples on the format of the array

deleteAll() public ¶

deleteAll( mixed $conditions )

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
integer
Returns the number of affected rows.
See
\Cake\ORM\Table::deleteAll()

dependent() public deprecated ¶

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.

Deprecated
3.4.0 Use setDependent()/getDependent() instead.
Parameters
boolean|null $dependent optional null
Set the dependent mode. Use null to read the current state.
Returns
boolean

exists() public ¶

exists( array|callable|Cake\Database\ExpressionInterface $conditions )

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

Parameters
array|callable|Cake\Database\ExpressionInterface $conditions

The conditions to use for checking if any record matches.

Returns
boolean
See
\Cake\ORM\Table::exists()

finder() public deprecated ¶

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.

Deprecated
3.4.0 Use setFinder()/getFinder() instead.
Parameters
string|null $finder optional null
the finder name to use
Returns
string|array

foreignKey() public deprecated ¶

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

Deprecated
3.4.0 Use setForeignKey()/getForeignKey() instead.
Parameters
string|null $key optional null
the key to be used to link both tables together
Returns
string|array

getBindingKey() public ¶

getBindingKey( )

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

Returns
string|string[]

getCascadeCallbacks() public ¶

getCascadeCallbacks( )

Gets whether or not cascaded deletes should also fire callbacks.

Returns
boolean

getClassName() public ¶

getClassName( )

Gets the class name of the target table object.

Returns
string

getConditions() public ¶

getConditions( )

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

Returns
array|callable
See
\Cake\Database\Query::where() for examples on the format of the array

getDependent() public ¶

getDependent( )

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.

Returns
boolean

getFinder() public ¶

getFinder( )

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

Returns
string|array

getJoinType() public ¶

getJoinType( )

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

Returns
string

getName() public ¶

getName( )

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

Returns
string

getProperty() public ¶

getProperty( )

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

Returns
string

getSource() public ¶

getSource( )

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

Returns
Cake\ORM\Table

getStrategy() public ¶

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.

Returns
string

getTarget() public ¶

getTarget( )

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

Returns
Cake\ORM\Table

joinType() public deprecated ¶

joinType( string|null $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.

Deprecated
3.4.0 Use setJoinType()/getJoinType() instead.
Parameters
string|null $type optional null
the join type to be used (e.g. INNER)
Returns
string

name() public deprecated ¶

name( string|null $name = null )

Sets the name for this association.

Deprecated
3.4.0 Use setName()/getName() instead.
Parameters
string|null $name optional null
Name to be assigned
Returns
string

property() public deprecated ¶

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.

Deprecated
3.4.0 Use setProperty()/getProperty() instead.
Parameters
string|null $name optional null
The name of the association property. Use null to read the current value.
Returns
string

requiresKeys() public ¶

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.

Parameters
array $options optional []
The options containing the strategy to be used.
Returns
boolean
true if a list of keys will be required

setBindingKey() public ¶

setBindingKey( string|string[] $key )

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.

Parameters
string|string[] $key
the table field or fields to be used to link both tables together
Returns

$this

setCascadeCallbacks() public ¶

setCascadeCallbacks( boolean $cascadeCallbacks )

Sets whether or not cascaded deletes should also fire callbacks.

Parameters
boolean $cascadeCallbacks
cascade callbacks switch value
Returns

$this

setClassName() public ¶

setClassName( string $className )

Sets the class name of the target table object.

Parameters
string $className
Class name to set.
Returns

$this
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.


setDependent() public ¶

setDependent( boolean $dependent )

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
boolean $dependent
Set the dependent mode. Use null to read the current state.
Returns

$this

setFinder() public ¶

setFinder( string|array $finder )

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

Parameters
string|array $finder
the finder name to use or array of finder name and option.
Returns

$this

setForeignKey() public ¶

setForeignKey( string|string[] $key )

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

Parameters
string|string[] $key
the key or keys to be used to link both tables together
Returns

$this

setJoinType() public ¶

setJoinType( string $type )

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

Parameters
string $type
the join type to be used (e.g. INNER)
Returns

$this

setName() public ¶

setName( string $name )

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

Parameters
string $name
Name to be assigned
Returns

$this

setProperty() public ¶

setProperty( string $name )

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

Parameters
string $name
The name of the association property. Use null to read the current value.
Returns

$this

setSource() public ¶

setSource( Cake\ORM\Table $table )

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

Parameters
Cake\ORM\Table $table
the instance to be assigned as source side
Returns

$this

setStrategy() public ¶

setStrategy( string $name )

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.

Parameters
string $name
The strategy type. Use null to read the current value.
Returns

$this
Throws
InvalidArgumentException
When an invalid strategy is provided.

setTarget() public ¶

setTarget( Cake\ORM\Table $table )

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

Parameters
Cake\ORM\Table $table
the instance to be assigned as target side
Returns

$this

source() public deprecated ¶

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

Deprecated
3.4.0 Use setSource()/getSource() instead.
Parameters
Cake\ORM\Table $table optional null
the instance to be assigned as source side
Returns
Cake\ORM\Table

strategy() public deprecated ¶

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.

Deprecated
3.4.0 Use setStrategy()/getStrategy() instead.
Parameters
string|null $name optional null
The strategy type. Use null to read the current value.
Returns
string
Throws
InvalidArgumentException
When an invalid strategy is provided.

target() public deprecated ¶

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

Deprecated
3.4.0 Use setTarget()/getTarget() instead.
Parameters
Cake\ORM\Table $table optional null
the instance to be assigned as target side
Returns
Cake\ORM\Table

transformRow() public ¶

transformRow( array $row , string $nestKey , boolean $joined , string|null $targetProperty = null )

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

Parameters
array $row
The row to transform
string $nestKey

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

boolean $joined

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

string|null $targetProperty optional null

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

Returns
array

updateAll() public ¶

updateAll( array $fields , mixed $conditions )

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
integer
Count Returns the affected rows.
See
\Cake\ORM\Table::updateAll()

Methods used from Cake\Core\ConventionsTrait

_camelize() protected ¶

_camelize( string $name )

Creates a camelized version of $name

Parameters
string $name
name
Returns
string
Camelized name

_entityName() protected ¶

_entityName( string $name )

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

Parameters
string $name
Name
Returns
string
Camelized and plural model name

_fixtureName() protected ¶

_fixtureName( string $name )

Creates a fixture name

Parameters
string $name
Model class name
Returns
string
Singular model key

_modelKey() protected ¶

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

Parameters
string $name
Model class name
Returns
string
Singular model key

_modelNameFromKey() protected ¶

_modelNameFromKey( string $key )

Creates the proper model name from a foreign key

Parameters
string $key
Foreign key
Returns
string
Model name

_pluginNamespace() protected ¶

_pluginNamespace( string $pluginName )

Return plugin's namespace

Parameters
string $pluginName
Plugin name
Returns
string
Plugin's namespace

_pluginPath() protected ¶

_pluginPath( string $pluginName )

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
path path to the correct plugin.

_pluralHumanName() protected ¶

_pluralHumanName( string $name )

Creates the plural human name used in views

Parameters
string $name
Controller name
Returns
string
Plural human name

_singularHumanName() protected ¶

_singularHumanName( string $name )

Creates the singular human name used in views

Parameters
string $name
Controller name
Returns
string
Singular human name

_singularName() protected ¶

_singularName( string $name )

Creates the singular name for use in views.

Parameters
string $name
Name to use
Returns
string
Variable name

_variableName() protected ¶

_variableName( string $name )

Creates the plural variable name for views

Parameters
string $name
Name to use
Returns
string
Plural name for views

Methods used from Cake\ORM\Locator\LocatorAwareTrait

getTableLocator() public ¶

getTableLocator( )

Gets the table locator.

Returns
Cake\ORM\Locator\LocatorInterface

setTableLocator() public ¶

setTableLocator( Cake\ORM\Locator\LocatorInterface $tableLocator )

Sets the table locator.

Parameters
Cake\ORM\Locator\LocatorInterface $tableLocator
LocatorInterface instance.
Returns

$this

tableLocator() public deprecated ¶

tableLocator( Cake\ORM\Locator\LocatorInterface $tableLocator = null )

Sets the table locator. If no parameters are passed, it will return the currently used locator.

Deprecated
3.5.0 Use getTableLocator()/setTableLocator() instead.
Parameters
Cake\ORM\Locator\LocatorInterface $tableLocator optional null
LocatorInterface instance.
Returns
Cake\ORM\Locator\LocatorInterface

Properties detail

$_dependent ¶

protected boolean

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.

true

$_joinType ¶

protected string

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

Cake\ORM\Association\QueryInterface::JOIN_TYPE_INNER

$_junctionAssociationName ¶

protected string

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

$_junctionConditions ¶

protected array|null

Filtered conditions that reference 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

'_joinData'

$_junctionTable ¶

protected Cake\ORM\Table

Junction table instance

$_junctionTableName ¶

protected string

Junction table name

$_saveStrategy ¶

protected string

Saving strategy to be used by this association

self::SAVE_REPLACE

$_sort ¶

protected mixed

Order in which target records should be returned

$_strategy ¶

protected string

The strategy name to be used to fetch associated records.

self::STRATEGY_SELECT

$_targetConditions ¶

protected array|null

Filtered conditions that reference the target table.

$_targetForeignKey ¶

protected string|string[]

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

$_through ¶

protected string|Cake\ORM\Table

The table instance for the junction relation.

$_validStrategies ¶

protected array

Valid strategies for this type of association

[
    self::STRATEGY_SELECT,
    self::STRATEGY_SUBQUERY
]
Follow @CakePHP
#IRC
OpenHub
Rackspace
  • Business Solutions
  • Showcase
  • Documentation
  • Book
  • API
  • Videos
  • Logos & Trademarks
  • Community
  • Team
  • Issues (Github)
  • YouTube Channel
  • Get Involved
  • Bakery
  • Featured Resources
  • Newsletter
  • Certification
  • My CakePHP
  • CakeFest
  • Facebook
  • Twitter
  • Help & Support
  • Forum
  • Stack Overflow
  • IRC
  • Slack
  • Paid Support

Generated using CakePHP API Docs