Class BelongsTo

Represents an 1 - N relationship where the source side of the relation is related to only one record in the target table.

An example of a BelongsTo association would be Article belongs to Author.

Cake\ORM\Association uses Cake\Core\ConventionsTrait, Cake\ORM\Locator\LocatorAwareTrait
Extended by Cake\ORM\Association\BelongsTo uses Cake\ORM\Association\SelectableAssociationTrait

Method Detail

_buildResultMapsource protected

_buildResultMap( mixed $fetchQuery , mixed $options )

_joinConditionsource protected

_joinCondition( array $options )

Returns a single or multiple conditions to be appended to the generated join clause for getting the results on the target table.

Parameters

array $options
list of options passed to attachTo method

Returns

array
array

Throws

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

Overrides

Cake\ORM\Association::_joinCondition()

_linkFieldsource protected

_linkField( mixed $options )

cascadeDeletesource public

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

Handle cascading deletes.

BelongsTo associations are never cleared in a cascading delete scenario.

Parameters

Cake\Datasource\EntityInterface $entity
The entity that started the cascaded delete.
array $options optional []
The options for the original delete.

Returns

boolean
Success.

foreignKeysource public

foreignKey( 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

Parameters

string|null $key optional null
the key to be used to link both tables together

Returns

string
string

Overrides

Cake\ORM\Association::foreignKey()

isOwningSidesource public

isOwningSide( Cake\ORM\Table $side )

Returns whether or not the passed table is the owning side for this association. This means that rows in the 'target' table would miss important or required information if the row in 'source' did not exist.

Parameters

Cake\ORM\Table $side
The potential Table with ownership

Returns

boolean
bool

propertysource public

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, currently configured type is returned.

Parameters

string|null $name optional null
The property name, use null to read the current property.

Returns

string
string

Overrides

Cake\ORM\Association::property()

saveAssociatedsource 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

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

See

Table::save()

typesource public

type( )

Get the relationship type.

Returns

string
string

Methods inherited from Cake\ORM\Association

__callsource 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
mixed

Throws

BadMethodCallException
\BadMethodCallException

__constructsource 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

__getsource 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
\Cake\ORM\Association

Throws

RuntimeException
if no association with such name exists

__issetsource 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

_appendFieldssource 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

_appendNotMatchingsource protected

_appendNotMatching( Cake\Database\Query $query , array $options )

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

Parameters

Cake\Database\Query $query
The query to modify
array $options
Options array containing the negateMatch key.

_bindNewAssociationssource 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

_dispatchBeforeFindsource 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

_extractFindersource 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
array

_formatAssociationResultssource 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

_optionssource protected

_options( array $options )

Override this function to initialize any concrete association class, it will get passed the original list of options used in the constructor

Parameters

array $options
List of options used for initialization

attachTosource 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, this will be merged with any conditions originally configured for this association
  • 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) the records found on this association
  • aliasPath: A dot separated string representing the path of association names followed from the passed query main table to this association.
  • propertyPath: A dot separated string representing the path of association properties to be followed from the passed query main entity to this association
  • joinType: The SQL join type to use in the query.
  • negateMatch: Will append a condition to the passed query for excluding matches. with this association.

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

bindingKeysource public

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

Parameters

string|null $key optional null
the table field to be used to link both tables together

Returns

string|array
string|array

canBeJoinedsource 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
bool

cascadeCallbackssource public

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

Parameters

boolean|null $cascadeCallbacks optional null
cascade callbacks switch value

Returns

boolean
bool

conditionssource public

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

Parameters

array|null $conditions optional null
list of conditions to be used

Returns

array
array

See

\Cake\Database\Query::where() for examples on the format of the array

defaultRowValuesource 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
array

deleteAllsource 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

boolean
Success Returns true if one or more rows are affected.

See

Cake\ORM\Table::deleteAll()

dependentsource public

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.

Parameters

boolean|null $dependent optional null
Set the dependent mode. Use null to read the current state.

Returns

boolean
bool

eagerLoadersource abstract 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.

The required way of passing related source records is controlled by "strategy" When the subquery strategy is used it will require a query on the source table. When using the select strategy, the list of primary keys will be used.

Returns a closure that should be run for each record returned in a specific Query. This callable will be responsible for injecting the fields that are related to each specific passed row.

Options array accepts the following keys:

  • query: Query object setup to find the source table records
  • keys: List of primary key values from the source table
  • foreignKey: The name of the field used to relate both tables
  • conditions: List of conditions to be passed to the query where() method
  • sort: The direction in which the records should be returned
  • fields: List of fields to select from the target table
  • contain: List of related tables to eager load associated to the target table
  • strategy: The name of strategy to use for finding target table records
  • nestKey: The array key under which results will be found when transforming the row

Parameters

array $options
The options for eager loading.

Returns

Closure
\Closure

findsource public

find( string|array $type null , array $options [] )

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

Parameters

string|array $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
\Cake\ORM\Query

See

Cake\ORM\Table::find()

findersource public

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.

Parameters

string|null $finder optional null
the finder name to use

Returns

string
string

joinTypesource public

joinType( string $type null )

Sets the type of join to be used when adding the association to a query. If no arguments are passed, the currently configured type is returned.

Parameters

string $type optional null
the join type to be used (e.g. INNER)

Returns

string
string

namesource public

name( string|null $name null )

Sets the name for this association. If no argument is passed then the current configured name will be returned

Parameters

string|null $name optional null
Name to be assigned

Returns

string
string

sourcesource public

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

Parameters

Cake\ORM\Table $table optional null
the instance to be assigned as source side

Returns

Cake\ORM\Table
\Cake\ORM\Table

strategysource public

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.

Parameters

string|null $name optional null
The strategy type. Use null to read the current value.

Returns

string
string

Throws

InvalidArgumentException
When an invalid strategy is provided.

targetsource public

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

Parameters

Cake\ORM\Table $table optional null
the instance to be assigned as target side

Returns

Cake\ORM\Table
\Cake\ORM\Table

transformRowsource public

transformRow( array $row , string $nestKey , boolean $joined )

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

Returns

array
array

updateAllsource 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

boolean
Success Returns true if one or more rows are affected.

See

Cake\ORM\Table::updateAll()

Methods used from Cake\ORM\Association\SelectableAssociationTrait

_addFilteringConditionsource protected

_addFilteringCondition( Cake\ORM\Query $query , string|array $key , mixed $filter )

Appends any conditions required to load the relevant set of records in the target table query given a filter key and some filtering values.

Parameters

Cake\ORM\Query $query
Target table's query
string|array $key
the fields that should be used for filtering
mixed $filter
the value that should be used to match for $key

Returns

Cake\ORM\Query
\Cake\ORM\Query

_addFilteringJoinsource public

_addFilteringJoin( Cake\ORM\Query $query , string $key , Cake\ORM\Query $subquery )

Appends any conditions required to load the relevant set of records in the target table query given a filter key and some filtering values when the filtering needs to be done using a subquery.

Parameters

Cake\ORM\Query $query
Target table's query
string $key
the fields that should be used for filtering
Cake\ORM\Query $subquery
The Subquery to use for filtering

Returns

Cake\ORM\Query
\Cake\ORM\Query

_buildQuerysource protected

_buildQuery( array $options )

Auxiliary function to construct a new Query object to return all the records in the target table that are associated to those specified in $options from the source table

Parameters

array $options
options accepted by eagerLoader()

Returns

Cake\ORM\Query
\Cake\ORM\Query

Throws

InvalidArgumentException
When a key is required for associations but not selected.

_buildSubquerysource protected

_buildSubquery( Cake\ORM\Query $query )

Builds a query to be used as a condition for filtering records in the target table, it is constructed by cloning the original query that was used to load records in the source table.

Parameters

Cake\ORM\Query $query
the original query used to load source records

Returns

Cake\ORM\Query
\Cake\ORM\Query

_createTupleConditionsource protected

_createTupleCondition( Cake\ORM\Query $query , array $keys , mixed $filter , string $operator )

Returns a TupleComparison object that can be used for matching all the fields from $keys with the tuple values in $filter using the provided operator.

Parameters

Cake\ORM\Query $query
Target table's query
array $keys
the fields that should be used for filtering
mixed $filter
the value that should be used to match for $key
string $operator
The operator for comparing the tuples

Returns

Cake\Database\Expression\TupleComparison
\Cake\Database\Expression\TupleComparison

_defaultOptionssource protected

_defaultOptions( )

Returns the default options to use for the eagerLoader

Returns

array
array

_multiKeysInjectorsource protected

_multiKeysInjector( array $resultMap , array $sourceKeys , string $nestKey )

Returns a callable to be used for each row in a query result set for injecting the eager loaded rows when the matching needs to be done with multiple foreign keys

Parameters

array $resultMap
A keyed arrays containing the target table
array $sourceKeys
An array with aliased keys to match
string $nestKey
The key under which results should be nested

Returns

Closure
\Closure

_resultInjectorsource protected

_resultInjector( Cake\ORM\Query $fetchQuery , array $resultMap , array $options )

Returns a callable to be used for each row in a query result set for injecting the eager loaded rows

Parameters

Cake\ORM\Query $fetchQuery
the Query used to fetch results
array $resultMap
an array with the foreignKey as keys and the corresponding target table results as value.
array $options
The options passed to the eagerLoader method

Returns

Closure
\Closure

_subqueryFieldssource protected

_subqueryFields( Cake\ORM\Query $query )

Calculate the fields that need to participate in a subquery.

Normally this includes the binding key columns. If there is a an ORDER BY, those columns are also included as the fields may be calculated or constant values, that need to be present to ensure the correct association data is loaded.

Parameters

Cake\ORM\Query $query
The query to get fields from.

Returns

array
The list of fields for the subquery.

eagerLoadersource public

eagerLoader( array $options )

requiresKeyssource 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

Methods used from Cake\Core\ConventionsTrait

_camelizesource protected

_camelize( string $name )

Creates a camelized version of $name

Parameters

string $name
name

Returns

string
Camelized name

_entityNamesource 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

_fixtureNamesource protected

_fixtureName( string $name )

Creates a fixture name

Parameters

string $name
Model class name

Returns

string
Singular model key

_modelKeysource 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

_modelNameFromKeysource protected

_modelNameFromKey( string $key )

Creates the proper model name from a foreign key

Parameters

string $key
Foreign key

Returns

string
Model name

_pluginNamespacesource protected

_pluginNamespace( string $pluginName )

Return plugin's namespace

Parameters

string $pluginName
Plugin name

Returns

string
Plugin's namespace

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

_pluralHumanNamesource protected

_pluralHumanName( string $name )

Creates the plural human name used in views

Parameters

string $name
Controller name

Returns

string
Plural human name

_singularHumanNamesource protected

_singularHumanName( string $name )

Creates the singular human name used in views

Parameters

string $name
Controller name

Returns

string
Singular human name

_singularNamesource protected

_singularName( string $name )

Creates the singular name for use in views.

Parameters

string $name
Name to use

Returns

string
Variable name

_variableNamesource 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

tableLocatorsource public

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

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

Parameters

Cake\ORM\Locator\LocatorInterface $tableLocator optional null
LocatorInterface instance.

Returns

Cake\ORM\Locator\LocatorInterface
\Cake\ORM\Locator\LocatorInterface

Constants inherited from Cake\ORM\Association

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

Properties summary

$_validStrategiessource

protected array

Valid strategies for this type of association

[self::STRATEGY_JOIN, self::STRATEGY_SELECT]

Properties inherited from Cake\ORM\Association

$_bindingKeysource

protected string|array

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

$_cascadeCallbackssource

protected string

Whether or not cascaded deletes should also fire callbacks.

false

$_classNamesource

protected string

The class name of the target table object

$_conditionssource

protected array

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

[]

$_dependentsource

protected boolean

Whether the records on the target table are dependent on the source table, often used to indicate that records should be removed if the owning record in the source table is deleted.

false

$_findersource

protected string

The default finder name to use for fetching rows from the target table

'all'

$_foreignKeysource

protected string|array

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

$_joinTypesource

protected string

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

'LEFT'

$_namesource

protected string

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

$_propertyNamesource

protected string

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

$_sourceTablesource

protected Cake\ORM\Table

Source table instance

$_strategysource

protected string

The strategy name to be used to fetch associated records. Some association types might not implement but one strategy to fetch records.

$_targetTablesource

protected Cake\ORM\Table

Target table instance

Properties used from Cake\ORM\Locator\LocatorAwareTrait

$_tableLocatorsource

protected Cake\ORM\Locator\LocatorInterface

Table locator instance

© 2005–2016 The Cake Software Foundation, Inc.
Licensed under the MIT License.
CakePHP is a registered trademark of Cake Software Foundation, Inc.
We are not endorsed by or affiliated with CakePHP.
http://api.cakephp.org/3.1/class-Cake.ORM.Association.BelongsTo.html