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.1 Red Velvet API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 3.1
      • 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
    • Console
      • Exception
    • Controller
      • Component
      • Exception
    • Core
      • Configure
        • Engine
      • Exception
    • Database
      • Driver
      • Exception
      • Expression
      • Schema
      • Statement
      • Type
    • Datasource
      • Exception
    • Error
    • Event
    • Filesystem
    • Form
    • I18n
      • Formatter
      • Parser
    • Log
      • Engine
    • Mailer
      • Exception
      • Transport
    • Network
      • Exception
      • Http
        • Adapter
        • Auth
        • FormData
      • Session
    • ORM
      • Association
      • Behavior
        • Translate
      • Exception
      • Locator
      • Rule
    • Routing
      • Exception
      • Filter
      • Route
    • Shell
      • Helper
      • Task
    • TestSuite
      • Fixture
      • Stub
    • Utility
      • Exception
    • Validation
    • View
      • Exception
      • Form
      • Helper
      • Widget
  • None

Classes

  • Association
  • AssociationCollection
  • Behavior
  • BehaviorRegistry
  • EagerLoader
  • Entity
  • Marshaller
  • Query
  • ResultSet
  • RulesChecker
  • Table
  • TableRegistry

Traits

  • AssociationsNormalizerTrait

Class Table

Represents a single database table.

Exposes methods for retrieving data out of it, and manages the associations this table has to other tables. Multiple instances of this class can be created for the same database table with different aliases, this allows you to address your database structure in a richer and more expressive way.

Retrieving data

The primary way to retrieve data is using Table::find(). See that method for more information.

Dynamic finders

In addition to the standard find($type) finder methods, CakePHP provides dynamic finder methods. These methods allow you to easily set basic conditions up. For example to filter users by username you would call

$query = $users->findByUsername('mark');

You can also combine conditions on multiple fields using either Or or And:

$query = $users->findByUsernameOrEmail('mark', 'mark@example.org');

Bulk updates/deletes

You can use Table::updateAll() and Table::deleteAll() to do bulk updates/deletes. You should be aware that events will not be fired for bulk updates/deletes.

Callbacks/events

Table objects provide a few callbacks/events you can hook into to augment/replace find operations. Each event uses the standard event subsystem in CakePHP

  • beforeFind(Event $event, Query $query, ArrayObject $options, boolean $primary) Fired before each find operation. By stopping the event and supplying a return value you can bypass the find operation entirely. Any changes done to the $query instance will be retained for the rest of the find. The $primary parameter indicates whether or not this is the root query, or an associated query.

  • buildValidator(Event $event, Validator $validator, string $name) Allows listeners to modify validation rules for the provided named validator.

  • buildRules(Event $event, RulesChecker $rules) Allows listeners to modify the rules checker by adding more rules.

  • beforeRules(Event $event, EntityInterface $entity, ArrayObject $options, string $operation) Fired before an entity is validated using the rules checker. By stopping this event, you can return the final value of the rules checking operation.

  • afterRules(Event $event, EntityInterface $entity, ArrayObject $options, bool $result, string $operation) Fired after the rules have been checked on the entity. By stopping this event, you can return the final value of the rules checking operation.

  • beforeSave(Event $event, EntityInterface $entity, ArrayObject $options) Fired before each entity is saved. Stopping this event will abort the save operation. When the event is stopped the result of the event will be returned.

  • afterSave(Event $event, EntityInterface $entity, ArrayObject $options) Fired after an entity is saved.

  • beforeDelete(Event $event, EntityInterface $entity, ArrayObject $options) Fired before an entity is deleted. By stopping this event you will abort the delete operation.

  • afterDelete(Event $event, EntityInterface $entity, ArrayObject $options) Fired after an entity has been deleted.

Cake\ORM\Table implements Cake\Datasource\RepositoryInterface, Cake\Event\EventListenerInterface, Cake\Event\EventDispatcherInterface uses Cake\Event\EventDispatcherTrait , Cake\Datasource\RulesAwareTrait , Cake\Validation\ValidatorAwareTrait
Namespace: Cake\ORM
See: \Cake\Event\EventManager for reference on the events system.
Location: ORM/Table.php

Constants summary

  • string
    DEFAULT_VALIDATOR ¶
    'default'
  • string
    RULES_CLASS ¶
    'Cake\ORM\RulesChecker'
  • string
    VALIDATOR_PROVIDER_NAME ¶
    'table'

Properties summary

  • $_alias protected
    string

    Human name giving to this particular instance. Multiple objects representing the same database table can exist by using different aliases.

  • $_associations protected
    Cake\ORM\AssociationCollection
    The associations container for this Table.
  • $_behaviors protected
    Cake\ORM\BehaviorRegistry
    BehaviorRegistry for this table
  • $_connection protected
    Cake\Datasource\ConnectionInterface
    Connection instance
  • $_displayField protected
    string
    The name of the field that represents a human readable representation of a row
  • $_entityClass protected
    string
    The name of the class that represent a single row for this table
  • $_primaryKey protected
    string|array
    The name of the field that represents the primary key in the table
  • $_registryAlias protected
    string
    Registry key used to create this table object
  • $_schema protected
    Cake\Database\Schema\Table
    The schema object containing a description of this table fields
  • $_table protected
    string
    Name of the table as it can be found in the database

Inherited Properties

  • _eventClass, _eventManager _rulesChecker _validatorClass, _validators

Method Summary

  • __call() public
    Handles behavior delegation + dynamic finders.
  • __construct() public
    Initializes a new instance
  • __debugInfo() public

    Returns an array that can be used to describe the internal state of this object.

  • __get() public

    Returns the association named after the passed value if exists, otherwise throws an exception.

  • __isset() public

    Returns whether an association named after the passed value exists for this table.

  • _dynamicFinder() protected
    Provides the dynamic findBy and findByAll methods.
  • _initializeSchema() protected

    Override this function in order to alter the schema used by this table. This function is only called after fetching the schema out of the database. If you wish to provide your own schema to this table without touching the database, you can override schema() or inject the definitions though that method.

  • _insert() protected
    Auxiliary function to handle the insert of an entity's data in the table
  • _newId() protected
    Generate a primary key value for a new record.
  • _processDelete() protected
    Perform the delete operation.
  • _processSave() protected
    Performs the actual saving of an entity based on the passed options.
  • _setFieldMatchers() protected

    Out of an options array, check if the keys described in $keys are arrays and change the values for closures that will concatenate the each of the properties in the value array when passed a row.

  • _update() protected
    Auxiliary function to handle the update of an entity's data in the table
  • addAssociations() public
    Setup multiple associations.
  • addBehavior() public
    Add a behavior.
  • alias() public
    Returns the table alias or sets a new one
  • aliasField() public
    Alias a field with the table's current alias.
  • association() public
    Returns an association object configured for the specified alias if any
  • associations() public
    Get the associations collection for this table.
  • behaviors() public
    Returns the behavior registry for this table.
  • belongsTo() public

    Creates a new BelongsTo association between this table and a target table. A "belongs to" association is a N-1 relationship where this table is the N side, and where there is a single associated record in the target table for each one in this table.

  • belongsToMany() public

    Creates a new BelongsToMany association between this table and a target table. A "belongs to many" association is a M-N relationship.

  • buildRules() public
  • callFinder() public

    Calls a finder method directly and applies it to the passed query, if no query is passed a new one will be created and returned

  • connection() public
    Returns the connection instance or sets a new one
  • defaultConnectionName() public static
    Get the default connection name.
  • delete() public
    Delete a single entity.
  • deleteAll() public
    Delete all matching records.
  • displayField() public
    Returns the display field or sets a new one
  • entityClass() public

    Returns the class used to hydrate rows for this table or sets a new one

  • exists() public

    Returns true if there is any record in this repository matching the specified conditions.

  • find() public

    Creates a new Query for this repository and applies some defaults based on the type of search that was selected.

  • findAll() public
    Returns the query as passed.
  • findList() public

    Sets up a query object so results appear as an indexed array, useful for any place where you would want a list such as for populating input select boxes.

  • findOrCreate() public
    Finds an existing record or creates a new one.
  • findThreaded() public

    Results for this finder will be a nested array, and is appropriate if you want to use the parent_id field of your model data to build nested results.

  • get() public

    Returns a single record after finding it by its primary key, if no record is found this method throws an exception.

  • hasBehavior() public
    Check if a behavior with the given alias has been loaded.
  • hasField() public
    Test to see if a Table has a specific field/column.
  • hasFinder() public
    Returns true if the finder exists for the table
  • hasMany() public

    Creates a new HasMany association between this table and a target table. A "has many" association is a 1-N relationship.

  • hasOne() public

    Creates a new HasOne association between this table and a target table. A "has one" association is a 1-1 relationship.

  • implementedEvents() public
    Get the Model callbacks this table is interested in.
  • initialize() public
    Initialize a table instance. Called after the constructor.
  • loadInto() public

    Loads the specified associations in the passed entity or list of entities by executing extra queries in the database and merging the results in the appropriate properties.

  • marshaller() public
    Get the object used to marshal/convert array data into objects.
  • newEntities() public
    Create a list of entities + associated entities from an array.
  • newEntity() public
    Create a new entity + associated entities from an array.
  • patchEntities() public

    Merges each of the elements passed in $data into the entities found in $entities respecting the accessible fields configured on the entities. Merging is done by matching the primary key in each of the elements in $data and $entities.

  • patchEntity() public

    Merges the passed $data into $entity respecting the accessible fields configured on the entity. Returns the same entity after being altered.

  • primaryKey() public
    Returns the primary key field name or sets a new one
  • query() public
    Creates a new Query instance for this repository
  • registryAlias() public
    Returns the table registry key used to create this table instance
  • removeBehavior() public
    Removes a behavior from this table's behavior registry.
  • save() public

    Persists an entity based on the fields that are marked as dirty and returns the same entity after a successful save or false in case of any error.

  • schema() public
    Returns the schema table object describing this table's properties.
  • table() public
    Returns the database table name or sets a new one
  • updateAll() public
    Update all matching records.
  • validateUnique() public

    Validator method used to check the uniqueness of a value for a column. This is meant to be used with the validation API and not to be called directly.

Method Detail

__call() public ¶

__call( string $method , array $args )

Handles behavior delegation + dynamic finders.

If your Table uses any behaviors you can call them as if they were on the table object.

Parameters
string $method
name of the method to be invoked
array $args
List of arguments passed to the function
Returns
mixed
Throws
BadMethodCallException

__construct() public ¶

__construct( array $config = [] )

Initializes a new instance

The $config array understands the following keys:

  • table: Name of the database table to represent
  • alias: Alias to be assigned to this table (default to table name)
  • connection: The connection instance to use
  • entityClass: The fully namespaced class name of the entity class that will represent rows in this table.
  • schema: A \Cake\Database\Schema\Table object or an array that can be passed to it.
  • eventManager: An instance of an event manager to use for internal events
  • behaviors: A BehaviorRegistry. Generally not used outside of tests.
  • associations: An AssociationCollection instance.
  • validator: A Validator instance which is assigned as the "default" validation set, or an associative array, where key is the name of the validation set and value the Validator instance.
Parameters
array $config optional []
List of options for this table

__debugInfo() public ¶

__debugInfo( )

Returns an array that can be used to describe the internal state of this object.

Returns
array

__get() public ¶

__get( string $property )

Returns the association named after the passed value if exists, otherwise throws an exception.

Parameters
string $property
the association name
Returns
Cake\ORM\Association
Throws
RuntimeException
if no association with such name exists

__isset() public ¶

__isset( string $property )

Returns whether an association named after the passed value exists for this table.

Parameters
string $property
the association name
Returns
boolean

_dynamicFinder() protected ¶

_dynamicFinder( string $method , array $args )

Provides the dynamic findBy and findByAll methods.

Parameters
string $method
The method name that was fired.
array $args
List of arguments passed to the function.
Returns
mixed
Throws
BadMethodCallException

when there are missing arguments, or when and & or are combined.


_initializeSchema() protected ¶

_initializeSchema( Cake\Database\Schema\Table $table )

Override this function in order to alter the schema used by this table. This function is only called after fetching the schema out of the database. If you wish to provide your own schema to this table without touching the database, you can override schema() or inject the definitions though that method.

Example:

protected function _initializeSchema(\Cake\Database\Schema\Table $table) {
 $table->columnType('preferences', 'json');
 return $table;
}
Parameters
Cake\Database\Schema\Table $table
The table definition fetched from database.
Returns
Cake\Database\Schema\Table
the altered schema
Api

_insert() protected ¶

_insert( Cake\Datasource\EntityInterface $entity , array $data )

Auxiliary function to handle the insert of an entity's data in the table

Parameters
Cake\Datasource\EntityInterface $entity
the subject entity from were $data was extracted
array $data
The actual data that needs to be saved
Returns
Cake\Datasource\EntityInterface|boolean
Throws
RuntimeException

if not all the primary keys where supplied or could be generated when the table has composite primary keys. Or when the table has no primary key.


_newId() protected ¶

_newId( array $primary )

Generate a primary key value for a new record.

By default, this uses the type system to generate a new primary key value if possible. You can override this method if you have specific requirements for id generation.

Parameters
array $primary
The primary key columns to get a new ID for.
Returns
mixed
Either null or the new primary key value.

_processDelete() protected ¶

_processDelete( Cake\Datasource\EntityInterface $entity , ArrayObject $options )

Perform the delete operation.

Will delete the entity provided. Will remove rows from any dependent associations, and clear out join tables for BelongsToMany associations.

Parameters
Cake\Datasource\EntityInterface $entity
The entity to delete.
ArrayObject $options
The options for the delete.
Returns
boolean
success
Throws
InvalidArgumentException

if there are no primary key values of the passed entity


_processSave() protected ¶

_processSave( Cake\Datasource\EntityInterface $entity , ArrayObject $options )

Performs the actual saving of an entity based on the passed options.

Parameters
Cake\Datasource\EntityInterface $entity
the entity to be saved
ArrayObject $options
the options to use for the save operation
Returns
Cake\Datasource\EntityInterface|boolean
Throws
RuntimeException
When an entity is missing some of the primary keys.

_setFieldMatchers() protected ¶

_setFieldMatchers( array $options , array $keys )

Out of an options array, check if the keys described in $keys are arrays and change the values for closures that will concatenate the each of the properties in the value array when passed a row.

This is an auxiliary function used for result formatters that can accept composite keys when comparing values.

Parameters
array $options
the original options passed to a finder
array $keys

the keys to check in $options to build matchers from the associated value

Returns
array

_update() protected ¶

_update( Cake\Datasource\EntityInterface $entity , array $data )

Auxiliary function to handle the update of an entity's data in the table

Parameters
Cake\Datasource\EntityInterface $entity
the subject entity from were $data was extracted
array $data
The actual data that needs to be saved
Returns
Cake\Datasource\EntityInterface|boolean
Throws
InvalidArgumentException
When primary key data is missing.

addAssociations() public ¶

addAssociations( array $params )

Setup multiple associations.

It takes an array containing set of table names indexed by association type as argument:

$this->Posts->addAssociations([
  'belongsTo' => [
    'Users' => ['className' => 'App\Model\Table\UsersTable']
  ],
  'hasMany' => ['Comments'],
  'belongsToMany' => ['Tags']
]);

Each association type accepts multiple associations where the keys are the aliases, and the values are association config data. If numeric keys are used the values will be treated as association aliases.

Parameters
array $params
Set of associations to bind (indexed by association type)
See
\Cake\ORM\Table::belongsTo()
\Cake\ORM\Table::hasOne()
\Cake\ORM\Table::hasMany()
\Cake\ORM\Table::belongsToMany()

addBehavior() public ¶

addBehavior( string $name , array $options = [] )

Add a behavior.

Adds a behavior to this table's behavior collection. Behaviors provide an easy way to create horizontally re-usable features that can provide trait like functionality, and allow for events to be listened to.

Example:

Load a behavior, with some settings.

$this->addBehavior('Tree', ['parent' => 'parentId']);

Behaviors are generally loaded during Table::initialize().

Parameters
string $name
The name of the behavior. Can be a short class reference.
array $options optional []
The options for the behavior to use.
Throws
RuntimeException
If a behavior is being reloaded.
See
Cake\ORM\Behavior

alias() public ¶

alias( string|null $alias = null )

Returns the table alias or sets a new one

Parameters
string|null $alias optional null
the new table alias
Returns
string
Implementation of
Cake\Datasource\RepositoryInterface::alias()

aliasField() public ¶

aliasField( string $field )

Alias a field with the table's current alias.

Parameters
string $field
The field to alias.
Returns
string
The field prefixed with the table alias.

association() public ¶

association( string $name )

Returns an association object configured for the specified alias if any

Parameters
string $name
the alias used for the association.
Returns
Cake\ORM\Association|null
Either the association or null.

associations() public ¶

associations( )

Get the associations collection for this table.

Returns
Cake\ORM\AssociationCollection
The collection of association objects.

behaviors() public ¶

behaviors( )

Returns the behavior registry for this table.

Returns
Cake\ORM\BehaviorRegistry
The BehaviorRegistry instance.

belongsTo() public ¶

belongsTo( string $associated , array $options = [] )

Creates a new BelongsTo association between this table and a target table. A "belongs to" association is a N-1 relationship where this table is the N side, and where there is a single associated record in the target table for each one in this table.

Target table can be inferred by its name, which is provided in the first argument, or you can either pass the to be instantiated or an instance of it directly.

The options array accept the following keys:

  • className: The class name of the target table object
  • targetTable: An instance of a table object to be used as the target table
  • 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
  • joinType: The type of join to be used (e.g. INNER)
  • strategy: The loading strategy to use. 'join' and 'select' are supported.
  • finder: The finder method to use when loading records from this association. Defaults to 'all'. When the strategy is 'join', only the fields, containments, and where conditions will be used from the finder.

This method will return the association object that was built.

Parameters
string $associated

the alias for the target table. This is used to uniquely identify the association

array $options optional []
list of options to configure the association definition
Returns
Cake\ORM\Association\BelongsTo

belongsToMany() public ¶

belongsToMany( string $associated , array $options = [] )

Creates a new BelongsToMany association between this table and a target table. A "belongs to many" association is a M-N relationship.

Target table can be inferred by its name, which is provided in the first argument, or you can either pass the class name to be instantiated or an instance of it directly.

The options array accept the following keys:

  • className: The class name of the target table object.
  • targetTable: An instance of a table object to be used as the target table.
  • foreignKey: The name of the field to use as foreign key.
  • targetForeignKey: The name of the field to use as the target foreign key.
  • joinTable: The name of the table representing the link between the two
  • through: If you choose to use an already instantiated link table, set this key to a configured Table instance containing associations to both the source and target tables in this association.
  • cascadeCallbacks: Set to true if you want CakePHP to fire callbacks on cascaded deletes. If false the ORM will use deleteAll() to remove data. When true join/junction table records will be loaded and then deleted.
  • conditions: array with a list of conditions to filter the join with.
  • sort: The order in which results for this association should be returned.
  • strategy: The strategy to be used for selecting results Either 'select' or 'subquery'. If subquery is selected the query used to return results in the source table will be used as conditions for getting rows in the target table.
  • saveStrategy: Either 'append' or 'replace'. Indicates the mode to be used for saving associated entities. The former will only create new links between both side of the relation and the latter will do a wipe and replace to create the links between the passed entities when saving.
  • strategy: The loading strategy to use. 'select' and 'subquery' are supported.
  • finder: The finder method to use when loading records from this association. Defaults to 'all'.

This method will return the association object that was built.

Parameters
string $associated

the alias for the target table. This is used to uniquely identify the association

array $options optional []
list of options to configure the association definition
Returns
Cake\ORM\Association\BelongsToMany

buildRules() public ¶

buildRules( Cake\ORM\RulesChecker $rules )

Parameters
Cake\ORM\RulesChecker $rules
The rules object to be modified.
Returns
Cake\ORM\RulesChecker

callFinder() public ¶

callFinder( string $type , Cake\ORM\Query $query , array $options = [] )

Calls a finder method directly and applies it to the passed query, if no query is passed a new one will be created and returned

Parameters
string $type
name of the finder to be called
Cake\ORM\Query $query
The query object to apply the finder options to
array $options optional []
List of options to pass to the finder
Returns
Cake\ORM\Query
Throws
BadMethodCallException

connection() public ¶

connection( Cake\Datasource\ConnectionInterface $conn = null )

Returns the connection instance or sets a new one

Parameters
Cake\Datasource\ConnectionInterface $conn optional null
The new connection instance
Returns
Cake\Datasource\ConnectionInterface

defaultConnectionName() public static ¶

defaultConnectionName( )

Get the default connection name.

This method is used to get the fallback connection name if an instance is created through the TableRegistry without a connection.

Returns
string
See
\Cake\ORM\TableRegistry::get()

delete() public ¶

delete( Cake\Datasource\EntityInterface $entity , array|ArrayAccess $options = [] )

Delete a single entity.

For HasMany and HasOne associations records will be removed based on the dependent option. Join table records in BelongsToMany associations will always be removed. You can use the cascadeCallbacks option when defining associations to change how associated data is deleted.

Options

  • atomic Defaults to true. When true the deletion happens within a transaction.
  • checkRules Defaults to true. Check deletion rules before deleting the record.

Events

  • Model.beforeDelete Fired before the delete occurs. If stopped the delete will be aborted. Receives the event, entity, and options.
  • Model.afterDelete Fired after the delete has been successful. Receives the event, entity, and options.
  • Model.afterDeleteCommit Fired after the transaction is committed for an atomic delete. Receives the event, entity, and options.

The options argument will be converted into an \ArrayObject instance for the duration of the callbacks, this allows listeners to modify the options used in the delete operation.

Parameters
Cake\Datasource\EntityInterface $entity
The entity to remove.
array|ArrayAccess $options optional []
The options for the delete.
Returns
boolean
success
Implementation of
Cake\Datasource\RepositoryInterface::delete()

deleteAll() public ¶

deleteAll( mixed $conditions )

Delete all matching records.

Parameters
mixed $conditions

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

Returns
integer
Count Returns the affected rows.
Implementation of
Cake\Datasource\RepositoryInterface::deleteAll()

displayField() public ¶

displayField( string|null $key = null )

Returns the display field or sets a new one

Parameters
string|null $key optional null
sets a new name to be used as display field
Returns
string

entityClass() public ¶

entityClass( string|null $name = null )

Returns the class used to hydrate rows for this table or sets a new one

Parameters
string|null $name optional null
the name of the class to use
Returns
string
Throws
Cake\ORM\Exception\MissingEntityException
when the entity class cannot be found

exists() public ¶

exists( array|ArrayAccess $conditions )

Returns true if there is any record in this repository matching the specified conditions.

Parameters
array|ArrayAccess $conditions
list of conditions to pass to the query
Returns
boolean
Implementation of
Cake\Datasource\RepositoryInterface::exists()

find() public ¶

find( string $type = 'all' , array|ArrayAccess $options = [] )

Creates a new Query for this repository and applies some defaults based on the type of search that was selected.

Model.beforeFind event

Each find() will trigger a Model.beforeFind event for all attached listeners. Any listener can set a valid result set using $query

By default, $options will recognize the following keys:

  • fields
  • conditions
  • order
  • limit
  • offset
  • page
  • group
  • having
  • contain
  • join

Usage

Using the options array:

$query = $articles->find('all', [
  'conditions' => ['published' => 1],
  'limit' => 10,
  'contain' => ['Users', 'Comments']
]);

Using the builder interface:

$query = $articles->find()
  ->where(['published' => 1])
  ->limit(10)
  ->contain(['Users', 'Comments']);

Calling finders

The find() method is the entry point for custom finder methods. You can invoke a finder by specifying the type:

$query = $articles->find('published');

Would invoke the findPublished method.

Parameters
string $type optional 'all'
the type of query to perform
array|ArrayAccess $options optional []
An array that will be passed to Query::applyOptions()
Returns
Cake\ORM\Query
The query builder
Implementation of
Cake\Datasource\RepositoryInterface::find()

findAll() public ¶

findAll( Cake\ORM\Query $query , array $options )

Returns the query as passed.

By default findAll() applies no conditions, you can override this method in subclasses to modify how find('all') works.

Parameters
Cake\ORM\Query $query
The query to find with
array $options
The options to use for the find
Returns
Cake\ORM\Query
The query builder

findList() public ¶

findList( Cake\ORM\Query $query , array $options )

Sets up a query object so results appear as an indexed array, useful for any place where you would want a list such as for populating input select boxes.

When calling this finder, the fields passed are used to determine what should be used as the array key, value and optionally what to group the results by. By default the primary key for the model is used for the key, and the display field as value.

The results of this finder will be in the following form:

[
 1 => 'value for id 1',
 2 => 'value for id 2',
 4 => 'value for id 4'
]

You can specify which property will be used as the key and which as value by using the $options array, when not specified, it will use the results of calling primaryKey and displayField respectively in this table:

$table->find('list', [
 'keyField' => 'name',
 'valueField' => 'age'
]);

Results can be put together in bigger groups when they share a property, you can customize the property to use for grouping by setting groupField:

$table->find('list', [
 'groupField' => 'category_id',
]);

When using a groupField results will be returned in this format:

[
 'group_1' => [
     1 => 'value for id 1',
     2 => 'value for id 2',
 ]
 'group_2' => [
     4 => 'value for id 4'
 ]
]
Parameters
Cake\ORM\Query $query
The query to find with
array $options
The options for the find
Returns
Cake\ORM\Query
The query builder

findOrCreate() public ¶

findOrCreate( array $search , callable $callback = null )

Finds an existing record or creates a new one.

Using the attributes defined in $search a find() will be done to locate an existing record. If records matches the conditions, the first record will be returned.

If no record can be found, a new entity will be created with the $search properties. If a callback is provided, it will be called allowing you to define additional default values. The new entity will be saved and returned.

Parameters
array $search
The criteria to find existing records by.
callable $callback optional null

A callback that will be invoked for newly created entities. This callback will be called before the entity is persisted.

Returns
Cake\Datasource\EntityInterface
An entity.

findThreaded() public ¶

findThreaded( Cake\ORM\Query $query , array $options )

Results for this finder will be a nested array, and is appropriate if you want to use the parent_id field of your model data to build nested results.

Values belonging to a parent row based on their parent_id value will be recursively nested inside the parent row values using the children property

You can customize what fields are used for nesting results, by default the primary key and the parent_id fields are used. If you wish to change these defaults you need to provide the keys keyField or parentField in $options:

$table->find('threaded', [
 'keyField' => 'id',
 'parentField' => 'ancestor_id'
]);
Parameters
Cake\ORM\Query $query
The query to find with
array $options
The options to find with
Returns
Cake\ORM\Query
The query builder

get() public ¶

get( mixed $primaryKey , array|ArrayAccess $options = [] )

Returns a single record after finding it by its primary key, if no record is found this method throws an exception.

Usage

Get an article and some relationships:

$article = $articles->get(1, ['contain' => ['Users', 'Comments']]);
Parameters
mixed $primaryKey
primary key value to find
array|ArrayAccess $options optional []
options accepted by Table::find()
Returns
Cake\Datasource\EntityInterface
Throws
Cake\Datasource\Exception\InvalidPrimaryKeyException

When $primaryKey has an incorrect number of elements.


Implementation of
Cake\Datasource\RepositoryInterface::get()

hasBehavior() public ¶

hasBehavior( string $name )

Check if a behavior with the given alias has been loaded.

Parameters
string $name
The behavior alias to check.
Returns
boolean
Whether or not the behavior exists.

hasField() public ¶

hasField( string $field )

Test to see if a Table has a specific field/column.

Delegates to the schema object and checks for column presence using the Schema\Table instance.

Parameters
string $field
The field to check for.
Returns
boolean
True if the field exists, false if it does not.
Implementation of
Cake\Datasource\RepositoryInterface::hasField()

hasFinder() public ¶

hasFinder( string $type )

Returns true if the finder exists for the table

Parameters
string $type
name of finder to check
Returns
boolean

hasMany() public ¶

hasMany( string $associated , array $options = [] )

Creates a new HasMany association between this table and a target table. A "has many" association is a 1-N relationship.

Target table can be inferred by its name, which is provided in the first argument, or you can either pass the class name to be instantiated or an instance of it directly.

The options array accept the following keys:

  • className: The class name of the target table object
  • targetTable: An instance of a table object to be used as the target table
  • foreignKey: The name of the field to use as foreign key, if false none will be used
  • dependent: Set to true if you want CakePHP to cascade deletes to the associated table when an entity is removed on this table. Set to false if you don't want CakePHP to remove associated data, for when you are using database constraints.
  • cascadeCallbacks: Set to true if you want CakePHP to fire callbacks on cascaded deletes. If false the ORM will use deleteAll() to remove data. When true records will be loaded and then deleted.
  • conditions: array with a list of conditions to filter the join with
  • sort: The order in which results for this association should be returned
  • saveStrategy: Either 'append' or 'replace'. When 'append' the current records are appended to any records in the database. When 'replace' associated records not in the current set will be removed. If the foreign key is a null able column or if dependent is true records will be orphaned.
  • strategy: The strategy to be used for selecting results Either 'select' or 'subquery'. If subquery is selected the query used to return results in the source table will be used as conditions for getting rows in the target table.
  • finder: The finder method to use when loading records from this association. Defaults to 'all'.

This method will return the association object that was built.

Parameters
string $associated

the alias for the target table. This is used to uniquely identify the association

array $options optional []
list of options to configure the association definition
Returns
Cake\ORM\Association\HasMany

hasOne() public ¶

hasOne( string $associated , array $options = [] )

Creates a new HasOne association between this table and a target table. A "has one" association is a 1-1 relationship.

Target table can be inferred by its name, which is provided in the first argument, or you can either pass the class name to be instantiated or an instance of it directly.

The options array accept the following keys:

  • className: The class name of the target table object
  • targetTable: An instance of a table object to be used as the target table
  • foreignKey: The name of the field to use as foreign key, if false none will be used
  • dependent: Set to true if you want CakePHP to cascade deletes to the associated table when an entity is removed on this table. Set to false if you don't want CakePHP to remove associated data, for when you are using database constraints.
  • cascadeCallbacks: Set to true if you want CakePHP to fire callbacks on cascaded deletes. If false the ORM will use deleteAll() to remove data. When true records will be loaded and then deleted.
  • conditions: array with a list of conditions to filter the join with
  • joinType: The type of join to be used (e.g. LEFT)
  • strategy: The loading strategy to use. 'join' and 'select' are supported.
  • finder: The finder method to use when loading records from this association. Defaults to 'all'. When the strategy is 'join', only the fields, containments, and where conditions will be used from the finder.

This method will return the association object that was built.

Parameters
string $associated

the alias for the target table. This is used to uniquely identify the association

array $options optional []
list of options to configure the association definition
Returns
Cake\ORM\Association\HasOne

implementedEvents() public ¶

implementedEvents( )

Get the Model callbacks this table is interested in.

By implementing the conventional methods a table class is assumed to be interested in the related event.

Override this method if you need to add non-conventional event listeners. Or if you want you table to listen to non-standard events.

The conventional method map is:

  • Model.beforeMarshal => beforeMarshal
  • Model.beforeFind => beforeFind
  • Model.beforeSave => beforeSave
  • Model.afterSave => afterSave
  • Model.afterSaveCommit => afterSaveCommit
  • Model.beforeDelete => beforeDelete
  • Model.afterDelete => afterDelete
  • Model.afterDeleteCommit => afterDeleteCommit
  • Model.beforeRules => beforeRules
  • Model.afterRules => afterRules
Returns
array
Implementation of
Cake\Event\EventListenerInterface::implementedEvents()

initialize() public ¶

initialize( array $config )

Initialize a table instance. Called after the constructor.

You can use this method to define associations, attach behaviors define validation and do any other initialization logic you need.

public function initialize(array $config)
 {
     $this->belongsTo('Users');
     $this->belongsToMany('Tagging.Tags');
     $this->primaryKey('something_else');
 }
Parameters
array $config
Configuration options passed to the constructor

loadInto() public ¶

loadInto( Cake\Datasource\EntityInterface|array $entities , array $contain )

Loads the specified associations in the passed entity or list of entities by executing extra queries in the database and merging the results in the appropriate properties.

Example:

$user = $usersTable->get(1);
$user = $usersTable->loadInto($user, ['Articles.Tags', 'Articles.Comments']);
echo $user->articles[0]->title;

You can also load associations for multiple entities at once

Example:

$users = $usersTable->find()->where([...])->toList();
$users = $usersTable->loadInto($users, ['Articles.Tags', 'Articles.Comments']);
echo $user[1]->articles[0]->title;

The properties for the associations to be loaded will be overwritten on each entity.

Parameters
Cake\Datasource\EntityInterface|array $entities
a single entity or list of entities
array $contain
A contain() compatible array.
Returns
Cake\Datasource\EntityInterface|array
See
\Cake\ORM\Query::contain()

marshaller() public ¶

marshaller( )

Get the object used to marshal/convert array data into objects.

Override this method if you want a table object to use custom marshalling logic.

Returns
Cake\ORM\Marshaller
See
Cake\ORM\Marshaller

newEntities() public ¶

newEntities( array $data , array $options = [] )

Create a list of entities + associated entities from an array.

By default all the associations on this table will be hydrated. You can limit which associations are built, or include deeper associations using the options parameter:

$articles = $this->Articles->newEntities(
  $this->request->data(),
  ['associated' => ['Tags', 'Comments.Users']]
);

You can limit fields that will be present in the constructed entities by passing the fieldList option, which is also accepted for associations:

$articles = $this->Articles->newEntities($this->request->data(), [
 'fieldList' => ['title', 'body'],
 'associated' => ['Tags', 'Comments.Users' => ['fieldList' => 'username']]
 ]
);

You can use the Model.beforeMarshal event to modify request data before it is converted into entities.

Parameters
array $data
The data to build an entity with.
array $options optional []
A list of options for the objects hydration.
Returns
array
An array of hydrated records.
Implementation of
Cake\Datasource\RepositoryInterface::newEntities()

newEntity() public ¶

newEntity( array|null $data = null , array $options = [] )

Create a new entity + associated entities from an array.

By default all the associations on this table will be hydrated. You can limit which associations are built, or include deeper associations using the options parameter:

$article = $this->Articles->newEntity(
  $this->request->data(),
  ['associated' => ['Tags', 'Comments.Users']]
);

You can limit fields that will be present in the constructed entity by passing the fieldList option, which is also accepted for associations:

$article = $this->Articles->newEntity($this->request->data(), [
 'fieldList' => ['title', 'body'],
 'associated' => ['Tags', 'Comments.Users' => ['fieldList' => 'username']]
]
);

The fieldList option lets remove or restrict input data from ending up in the entity. If you'd like to relax the entity's default accessible fields, you can use the accessibleFields option:

$article = $this->Articles->newEntity(
  $this->request->data(),
  ['accessibleFields' => ['protected_field' => true]]
);

By default, the data is validated before being passed to the new entity. In the case of invalid fields, those will not be present in the resulting object. The validate option can be used to disable validation on the passed data:

$article = $this->Articles->newEntity(
  $this->request->data(),
  ['validate' => false]
);

You can also pass the name of the validator to use in the validate option. If null is passed to the first param of this function, no validation will be performed.

You can use the Model.beforeMarshal event to modify request data before it is converted into entities.

Parameters
array|null $data optional null
The data to build an entity with.
array $options optional []
A list of options for the object hydration.
Returns
Cake\Datasource\EntityInterface
Implementation of
Cake\Datasource\RepositoryInterface::newEntity()

patchEntities() public ¶

patchEntities( array|Traversable $entities , array $data , array $options = [] )

Merges each of the elements passed in $data into the entities found in $entities respecting the accessible fields configured on the entities. Merging is done by matching the primary key in each of the elements in $data and $entities.

Those entries in $entities that cannot be matched to any record in $data will be discarded. Records in $data that could not be matched will be marshalled as a new entity.

When merging HasMany or BelongsToMany associations, all the entities in the $data array will appear, those that can be matched by primary key will get the data merged, but those that cannot, will be discarded.

You can limit fields that will be present in the merged entities by passing the fieldList option, which is also accepted for associations:

$articles = $this->Articles->patchEntities($articles, $this->request->data(), [
 'fieldList' => ['title', 'body'],
 'associated' => ['Tags', 'Comments.Users' => ['fieldList' => 'username']]
 ]
);

You can use the Model.beforeMarshal event to modify request data before it is converted into entities.

Parameters
array|Traversable $entities

the entities that will get the data merged in

array $data
list of arrays to be merged into the entities
array $options optional []
A list of options for the objects hydration.
Returns
array
Implementation of
Cake\Datasource\RepositoryInterface::patchEntities()

patchEntity() public ¶

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

Merges the passed $data into $entity respecting the accessible fields configured on the entity. Returns the same entity after being altered.

When merging HasMany or BelongsToMany associations, all the entities in the $data array will appear, those that can be matched by primary key will get the data merged, but those that cannot, will be discarded.

You can limit fields that will be present in the merged entity by passing the fieldList option, which is also accepted for associations:

$article = $this->Articles->patchEntity($article, $this->request->data(), [
 'fieldList' => ['title', 'body'],
 'associated' => ['Tags', 'Comments.Users' => ['fieldList' => 'username']]
 ]
);

By default, the data is validated before being passed to the entity. In the case of invalid fields, those will not be assigned to the entity. The validate option can be used to disable validation on the passed data:

$article = $this->patchEntity($article, $this->request->data(),[
 'validate' => false
]);

You can use the Model.beforeMarshal event to modify request data before it is converted into entities.

Parameters
Cake\Datasource\EntityInterface $entity

the entity that will get the data merged in

array $data
key value list of fields to be merged into the entity
array $options optional []
A list of options for the object hydration.
Returns
Cake\Datasource\EntityInterface
Implementation of
Cake\Datasource\RepositoryInterface::patchEntity()

primaryKey() public ¶

primaryKey( string|array|null $key = null )

Returns the primary key field name or sets a new one

Parameters
string|array|null $key optional null
sets a new name to be used as primary key
Returns
string|array

query() public ¶

query( )

Creates a new Query instance for this repository

Returns
Cake\ORM\Query
Implementation of
Cake\Datasource\RepositoryInterface::query()

registryAlias() public ¶

registryAlias( string|null $registryAlias = null )

Returns the table registry key used to create this table instance

Parameters
string|null $registryAlias optional null
the key used to access this object
Returns
string

removeBehavior() public ¶

removeBehavior( string $name )

Removes a behavior from this table's behavior registry.

Example:

Remove a behavior from this table.

$this->removeBehavior('Tree');
Parameters
string $name
The alias that the behavior was added with.
See
Cake\ORM\Behavior

save() public ¶

save( Cake\Datasource\EntityInterface $entity , array|ArrayAccess $options = [] )

Persists an entity based on the fields that are marked as dirty and returns the same entity after a successful save or false in case of any error.

Options

The options array accepts the following keys:

  • atomic: Whether to execute the save and callbacks inside a database transaction (default: true)
  • checkRules: Whether or not to check the rules on entity before saving, if the checking fails, it will abort the save operation. (default:true)
  • associated: If true it will save all associated entities as they are found in the passed $entity whenever the property defined for the association is marked as dirty. Associated records are saved recursively unless told otherwise. If an array, it will be interpreted as the list of associations to be saved. It is possible to provide different options for saving on associated table objects using this key by making the custom options the array value. If false no associated records will be saved. (default: true)
  • checkExisting: Whether or not to check if the entity already exists, assuming that the entity is marked as not new, and the primary key has been set.

Events

When saving, this method will trigger four events:

  • Model.beforeRules: Will be triggered right before any rule checking is done for the passed entity if the checkRules key in $options is not set to false. Listeners will receive as arguments the entity, options array and the operation type. If the event is stopped the rules check result will be set to the result of the event itself.
  • Model.afterRules: Will be triggered right after the checkRules() method is called for the entity. Listeners will receive as arguments the entity, options array, the result of checking the rules and the operation type. If the event is stopped the checking result will be set to the result of the event itself.
  • Model.beforeSave: Will be triggered just before the list of fields to be persisted is calculated. It receives both the entity and the options as arguments. The options array is passed as an ArrayObject, so any changes in it will be reflected in every listener and remembered at the end of the event so it can be used for the rest of the save operation. Returning false in any of the listeners will abort the saving process. If the event is stopped using the event API, the event object's result property will be returned. This can be useful when having your own saving strategy implemented inside a listener.
  • Model.afterSave: Will be triggered after a successful insert or save, listeners will receive the entity and the options array as arguments. The type of operation performed (insert or update) can be determined by checking the entity's method isNew, true meaning an insert and false an update.
  • Model.afterSaveCommit: Will be triggered after the transaction is commited for atomic save, listeners will receive the entity and the options array as arguments.

This method will determine whether the passed entity needs to be inserted or updated in the database. It does that by checking the isNew method on the entity. If the entity to be saved returns a non-empty value from its errors() method, it will not be saved.

Saving on associated tables

This method will by default persist entities belonging to associated tables, whenever a dirty property matching the name of the property name set for an association in this table. It is possible to control what associations will be saved and to pass additional option for saving them.

// Only save the comments association
$articles->save($entity, ['associated' => ['Comments']);

// Save the company, the employees and related addresses for each of them.
// For employees do not check the entity rules
$companies->save($entity, [
  'associated' => [
    'Employees' => [
      'associated' => ['Addresses'],
      'checkRules' => false
    ]
  ]
]);

// Save no associations
$articles->save($entity, ['associated' => false]);
Parameters
Cake\Datasource\EntityInterface $entity
the entity to be saved
array|ArrayAccess $options optional []
The options to use when saving.
Returns
Cake\Datasource\EntityInterface|boolean
Implementation of
Cake\Datasource\RepositoryInterface::save()

schema() public ¶

schema( array|Cake\Database\Schema\Table|null $schema = null )

Returns the schema table object describing this table's properties.

If an \Cake\Database\Schema\Table is passed, it will be used for this table instead of the default one.

If an array is passed, a new \Cake\Database\Schema\Table will be constructed out of it and used as the schema for this table.

Parameters
array|Cake\Database\Schema\Table|null $schema optional null
New schema to be used for this table
Returns
Cake\Database\Schema\Table

table() public ¶

table( string|null $table = null )

Returns the database table name or sets a new one

Parameters
string|null $table optional null
the new table name
Returns
string

updateAll() public ¶

updateAll( array $fields , mixed $conditions )

Update all matching records.

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.
Implementation of
Cake\Datasource\RepositoryInterface::updateAll()

validateUnique() public ¶

validateUnique( mixed $value , array $options , array $context = null )

Validator method used to check the uniqueness of a value for a column. This is meant to be used with the validation API and not to be called directly.

Example:

$validator->add('email', [
 'unique' => ['rule' => 'validateUnique', 'provider' => 'table']
])

Unique validation can be scoped to the value of another column:

$validator->add('email', [
 'unique' => [
     'rule' => ['validateUnique', ['scope' => 'site_id']],
     'provider' => 'table'
 ]
]);

In the above example, the email uniqueness will be scoped to only rows having the same site_id. Scoping will only be used if the scoping field is present in the data to be validated.

Parameters
mixed $value
The value of column to be checked for uniqueness
array $options

The options array, optionally containing the 'scope' key. May also be the validation context if there are no options.

array $context optional null
Either the validation context or null.
Returns
boolean
true if the value is unique

Methods used from Cake\Event\EventDispatcherTrait

dispatchEvent() public ¶

dispatchEvent( string $name , array|null $data = null , object|null $subject = null )

Wrapper for creating and dispatching events.

Returns a dispatched event.

Parameters
string $name
Name of the event.
array|null $data optional null

Any value you wish to be transported with this event to it can be read by listeners.

object|null $subject optional null

The object that this event applies to ($this by default).

Returns
Cake\Event\Event

eventManager() public ¶

eventManager( Cake\Event\EventManager $eventManager = null )

Returns the Cake\Event\EventManager manager instance for this object.

You can use this instance to register any new listeners or callbacks to the object events, or create your own events and trigger them at will.

Parameters
Cake\Event\EventManager $eventManager optional null
the eventManager to set
Returns
Cake\Event\EventManager

Methods used from Cake\Datasource\RulesAwareTrait

checkRules() public ¶

checkRules( Cake\Datasource\EntityInterface $entity , string $operation = RulesChecker::CREATE , ArrayObject|array $options = null )

Returns whether or not the passed entity complies with all the rules stored in the rules checker.

Parameters
Cake\Datasource\EntityInterface $entity
The entity to check for validity.
string $operation optional RulesChecker::CREATE
The operation being run. Either 'create', 'update' or 'delete'.
ArrayObject|array $options optional null
The options To be passed to the rules.
Returns
boolean

rulesChecker() public ¶

rulesChecker( )

Returns the RulesChecker for this instance.

A RulesChecker object is used to test an entity for validity on rules that may involve complex logic or data that needs to be fetched from relevant datasources.

Returns
Cake\Datasource\RulesChecker
See
Cake\Datasource\RulesChecker

Methods used from Cake\Validation\ValidatorAwareTrait

validationDefault() public ¶

validationDefault( Cake\Validation\Validator $validator )

Returns the default validator object. Subclasses can override this function to add a default validation set to the validator object.

Parameters
Cake\Validation\Validator $validator

The validator that can be modified to add some rules to it.

Returns
Cake\Validation\Validator

validator() public ¶

validator( string $name = null , Cake\Validation\Validator $validator = null )

Returns the validation rules tagged with $name. It is possible to have multiple different named validation sets, this is useful when you need to use varying rules when saving from different routines in your system.

There are two different ways of creating and naming validation sets: by creating a new method inside your own Table subclass, or by building the validator object yourself and storing it using this method.

For example, if you wish to create a validation set called 'forSubscription', you will need to create a method in your Table subclass as follows:

public function validationForSubscription($validator)
{
 return $validator
 ->add('email', 'valid-email', ['rule' => 'email'])
 ->add('password', 'valid', ['rule' => 'notBlank'])
 ->requirePresence('username');
}

Otherwise, you can build the object by yourself and store it in the Table object:

$validator = new \Cake\Validation\Validator($table);
$validator
 ->add('email', 'valid-email', ['rule' => 'email'])
 ->add('password', 'valid', ['rule' => 'notBlank'])
 ->allowEmpty('bio');
$table->validator('forSubscription', $validator);

You can implement the method in validationDefault in your Table subclass should you wish to have a validation set that applies in cases where no other set is specified.

Parameters
string $name optional null
the name of the validation set to return
Cake\Validation\Validator $validator optional null

The validator instance to store, use null to get a validator.

Returns
Cake\Validation\Validator

Properties detail

$_alias ¶

protected string

Human name giving to this particular instance. Multiple objects representing the same database table can exist by using different aliases.

$_associations ¶

protected Cake\ORM\AssociationCollection

The associations container for this Table.

$_behaviors ¶

protected Cake\ORM\BehaviorRegistry

BehaviorRegistry for this table

$_connection ¶

protected Cake\Datasource\ConnectionInterface

Connection instance

$_displayField ¶

protected string

The name of the field that represents a human readable representation of a row

$_entityClass ¶

protected string

The name of the class that represent a single row for this table

$_primaryKey ¶

protected string|array

The name of the field that represents the primary key in the table

$_registryAlias ¶

protected string

Registry key used to create this table object

$_schema ¶

protected Cake\Database\Schema\Table

The schema object containing a description of this table fields

$_table ¶

protected string

Name of the table as it can be found in the database

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