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. - afterSaveCommit(Event $event, EntityInterface $entity, ArrayObject $options) Fired after the transaction in which the save operation is wrapped has been committed. It’s also triggered for non atomic saves where database operations are implicitly committed. The event is triggered only for the primary table on which save() is directly called. The event is not triggered if a transaction is started before calling save. - 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.
See also: Cake\Event\EventManager for reference on the events system.
Inheritance: implements Cake\Datasource\RepositoryInterface, implements Cake\Event\EventListenerInterface, implements Cake\Event\EventDispatcherInterface, use trait Cake\Event\EventDispatcherTrait, use trait Cake\Datasource\RulesAwareTrait, use trait Cake\Validation\ValidatorAwareTrait
Exemplo n.º 1
1
 /**
  * Get the array of junction aliases for all the BelongsToMany associations
  *
  * @param Table $table Table
  * @return array junction aliases of all the BelongsToMany associations
  */
 public function belongsToManyJunctionAliases(Table $table)
 {
     $extractor = function ($val) {
         return $val->junction()->alias();
     };
     return array_map($extractor, $table->associations()->type('BelongsToMany'));
 }
Exemplo n.º 2
1
 /**
  * Extract the aliases for associations
  *
  * @param \Cake\ORM\Table $table object to find associations on
  * @param string $assoc association to extract
  * @return array
  */
 public function aliasExtractor($table, $assoc)
 {
     $extractor = function ($val) {
         return $val->target()->alias();
     };
     return array_map($extractor, $table->associations()->type($assoc));
 }
Exemplo n.º 3
1
 /**
  * @param \Cake\Event\Event $event
  * @param \Cake\ORM\Query $query
  * @param \ArrayObject $options
  * @param bool $primary
  * @return void
  */
 public function beforeFind(Event $event, Query $query, ArrayObject $options, $primary)
 {
     if (!$primary && !$this->_config['recursive']) {
         return;
     }
     $field = $this->_config['field'];
     if (!$field) {
         return;
     }
     $query->find('hashed');
     $idField = $this->_primaryKey;
     if ($primary && $field === $idField) {
         $query->traverseExpressions(function ($expression) {
             if (method_exists($expression, 'getField') && ($expression->getField() === $this->_primaryKey || $expression->getField() === $this->_table->alias() . '.' . $this->_primaryKey)) {
                 $expression->setValue($this->decodeHashid($expression->getValue()));
             }
             return $expression;
         });
     }
     if (!$this->_config['recursive']) {
         return;
     }
     foreach ($this->_table->associations() as $association) {
         if ($association->target()->hasBehavior('Hashid') && $association->finder() === 'all') {
             $association->finder('hashed');
         }
     }
 }
 /**
  * Method that renders Entity values through Field Handler Factory.
  *
  * @param  Cake\ORM\Entity       $entity    Entity instance
  * @param  Cake\ORM\Table|string $table     Table instance
  * @param  array                 $fields    Fields to prettify
  * @return void
  */
 protected function _prettify(Entity $entity, $table, array $fields = [])
 {
     if (!$this->__fhf instanceof FieldHandlerFactory) {
         $this->__fhf = new FieldHandlerFactory();
     }
     if (empty($fields)) {
         $fields = array_keys($entity->toArray());
     }
     foreach ($fields as $field) {
         // handle belongsTo associated data
         if ($entity->{$field} instanceof Entity) {
             $tableName = $table->association($entity->{$field}->source())->className();
             $this->_prettify($entity->{$field}, $tableName);
         }
         // handle hasMany associated data
         if (is_array($entity->{$field})) {
             if (empty($entity->{$field})) {
                 continue;
             }
             foreach ($entity->{$field} as $associatedEntity) {
                 if (!$associatedEntity instanceof Entity) {
                     continue;
                 }
                 $tableName = $table->association($associatedEntity->source())->className();
                 $this->_prettify($associatedEntity, $tableName);
             }
         }
         $renderOptions = ['entity' => $entity];
         $entity->{$field} = $this->__fhf->renderValue($table instanceof Table ? $table->registryAlias() : $table, $field, $entity->{$field}, $renderOptions);
     }
 }
Exemplo n.º 5
1
 /**
  * test WHERE conditions against unary expression.
  *
  * @return void
  */
 public function testUnaryExpression()
 {
     $this->table->addColumn('user-birth-date', ['type' => 'date'], false);
     $first = $this->table->get(1);
     $first->set('user-birth-date', time());
     $this->table->save($first);
     $second = $this->table->find('all', ['eav' => true])->where(['user-birth-date IS' => null])->order(['id' => 'ASC'])->first();
     $this->assertTrue(!empty($second) && $second->get('id') == 2);
 }
Exemplo n.º 6
1
 /**
  * testSendNewPasswordEmail
  *
  * @return void
  */
 public function testSendNewPasswordEmail()
 {
     $user = $this->Users->get(1);
     $this->Mailer->expects($this->once())->method('to')->with('*****@*****.**')->will($this->returnSelf());
     $this->Mailer->expects($this->once())->method('subject')->with('Your new password')->will($this->returnSelf());
     $this->Mailer->expects($this->once())->method('template')->with('Burzum/UserTools.Users/new_password')->will($this->returnSelf());
     $this->Mailer->expects($this->once())->method('set')->with('user', $user)->will($this->returnSelf());
     $this->Mailer->sendNewPasswordEmail($user);
 }
Exemplo n.º 7
1
 public function __construct(Table $table, Entity $entity, $field, array $settings)
 {
     $this->setRoot(TMP . 'ProfferTests');
     $this->setTable($table->alias());
     $this->setField($field);
     $this->setSeed('proffer_test');
     if (isset($settings['thumbnailSizes'])) {
         $this->setPrefixes($settings['thumbnailSizes']);
     }
     $this->setFilename($entity->get($field));
 }
Exemplo n.º 8
1
 /**
  * Constructor
  *
  * @param \Cake\ORM\Table $table Table who requested the behavior.
  * @param array $config Options.
  */
 public function __construct(Table $table, array $config = [])
 {
     parent::__construct($table, $config);
     $this->Table = $table;
     if ($this->config('created_by')) {
         $this->Table->belongsTo('CreatedBy', ['foreignKey' => $this->config('created_by'), 'className' => $this->config('userModel'), 'propertyName' => $this->config('createdByPropertyName')]);
     }
     if ($this->config('modified_by')) {
         $this->Table->belongsTo('ModifiedBy', ['foreignKey' => $this->config('modified_by'), 'className' => $this->config('userModel'), 'propertyName' => $this->config('modifiedByPropertyName')]);
     }
 }
Exemplo n.º 9
1
 /**
  * Generates a SQL sub-query for replacing in ORDER BY clause.
  *
  * @param string $column Name of the column being replaced by this sub-query
  * @param string|null $bundle Consider attributes only for a specific bundle
  * @return string SQL sub-query statement
  */
 protected function _subQuery($column, $bundle = null)
 {
     $alias = $this->_table->alias();
     $pk = $this->_table->primaryKey();
     $type = $this->_toolbox->getType($column);
     $subConditions = ['EavAttribute.table_alias' => $this->_table->table(), 'EavValues.entity_id' => "{$alias}.{$pk}", 'EavAttribute.name' => $column];
     if (!empty($bundle)) {
         $subConditions['EavAttribute.bundle'] = $bundle;
     }
     $subQuery = TableRegistry::get('Eav.EavValues')->find()->contain(['EavAttribute'])->select(["EavValues.value_{$type}"])->where($subConditions)->sql();
     return str_replace([':c0', ':c1', ':c2', ':c3'], ['"' . $this->_table->table() . '"', "{$alias}.{$pk}", '"' . $column . '"', '"' . $bundle . '"'], $subQuery);
 }
Exemplo n.º 10
0
 public function increment(Table $table, $counter, $identifier)
 {
     list($alias, $field) = $this->_counterSplit($counter);
     $key = $table->primaryKey();
     if ($table->alias() !== $alias) {
         $key = $table->{$alias}->bindingKey();
         $table = TableRegistry::get($alias);
     }
     $expression = new QueryExpression("{$field} = {$field} + " . $this->_offset);
     $conditions = [$key => $identifier] + $this->_conditions;
     return $table->updateAll($expression, $conditions);
 }
 /**
  * Constructor
  *
  * @param \Cake\ORM\Table $table Table instance
  * @param array $config Configuration
  */
 public function __construct(Table $table, array $config = [])
 {
     $tableAlias = $table->alias();
     list($plugin) = pluginSplit($table->registryAlias(), true);
     if (isset($config['referenceName'])) {
         $tableReferenceName = $config['referenceName'];
     } else {
         $tableReferenceName = $this->_referenceName($table);
     }
     $config += ['mainTableAlias' => $tableAlias, 'translationTable' => $plugin . $tableReferenceName . 'Translations', 'hasOneAlias' => $tableAlias . 'Translation'];
     parent::__construct($table, $config);
 }
Exemplo n.º 12
0
 /**
  * Setup modules for layout.
  *
  * @return void
  */
 private function __setForLayout()
 {
     $positions = $this->Theme->getThemePositions();
     $theme = Inflector::underscore(Configure::read('Theme.' . Theme::CLIENT_FRONT_END));
     foreach ($positions as $position) {
         $cacheKey = $theme . '_' . $position;
         $modules = $this->_table->find()->where(['position' => $position])->order(['ordering' => 'ASC'])->cache($cacheKey, 'positions')->toArray();
         if (!empty($modules)) {
             $this->_modulesForLayout[$position] = $modules;
         }
     }
     $this->_controller->set('module_for_layout', $this->_modulesForLayout);
 }
Exemplo n.º 13
0
 /**
  * Toggle field value.
  *
  * @param Table|\Cake\ORM\Table $table
  * @param string|int $id
  * @param string|int $value
  * @param string $field
  * @throw BadRequestException
  * @throw RuntimeException
  */
 public function fieldToggle($table, $id, $value, $field = self::TOGGLE_DEFAULT_FIELD)
 {
     $this->_checkIsAjax();
     $this->_checkToggleData($id, $value);
     $this->_controller->viewBuilder()->layout('ajax')->templatePath('Common');
     $entity = $table->get($id);
     $entity->{$field} = !(int) $value;
     if ($result = $table->save($entity)) {
         $this->_controller->set('record', $result);
         $this->_controller->render('toggle');
     } else {
         throw new RuntimeException(__d('union', 'Failed toggling field {0} to {1}', $field, $entity->{$field}));
     }
 }
 public function testFind()
 {
     $entities = [];
     foreach ($this->entityMap as $discriminator => $class) {
         $data = ['discriminator' => $discriminator];
         $entities[] = $this->table->newEntity($data);
     }
     $this->table->saveMany($entities);
     $found = $this->table->find()->toArray();
     $this->assertCount(6, $found);
     foreach ($found as $entity) {
         $class = $this->entityMap[$entity->discriminator];
         $this->assertInstanceOf($class, $entity);
     }
 }
Exemplo n.º 15
0
 /**
  * Returns the basepath for the current field/data combination.
  * If a `path` is specified in settings, then that will be used as
  * the replacement pattern
  *
  * @return string
  * @throws LogicException if a replacement is not valid for the current dataset
  */
 public function basepath()
 {
     $defaultPath = 'webroot{DS}files{DS}{model}{DS}{field}{DS}';
     $path = Hash::get($this->settings, 'path', $defaultPath);
     if (strpos($path, '{primaryKey}') !== false) {
         if ($this->entity->isNew()) {
             throw new LogicException('{primaryKey} substitution not allowed for new entities');
         }
         if (is_array($this->table->primaryKey())) {
             throw new LogicException('{primaryKey} substitution not valid for composite primary keys');
         }
     }
     $replacements = ['{primaryKey}' => $this->entity->get($this->table->primaryKey()), '{model}' => $this->table->alias(), '{relatedModel}' => $this->entity->model, '{table}' => $this->table->table(), '{field}' => $this->field, '{time}' => time(), '{microtime}' => microtime(), '{DS}' => DIRECTORY_SEPARATOR];
     return str_replace(array_keys($replacements), array_values($replacements), $path);
 }
Exemplo n.º 16
0
 /**
  * Construct the class and setup the defaults
  *
  * @param Table $table Instance of the table
  * @param Entity $entity Instance of the entity data
  * @param string $field The name of the upload field
  * @param array $settings Array of settings for the upload field
  */
 public function __construct(Table $table, Entity $entity, $field, array $settings)
 {
     if (isset($settings['root'])) {
         $this->setRoot($settings['root']);
     } else {
         $this->setRoot(WWW_ROOT . 'files');
     }
     $this->setTable($table->alias());
     $this->setField($field);
     $this->setSeed($this->generateSeed($entity->get($settings['dir'])));
     if (isset($settings['thumbnailSizes'])) {
         $this->setPrefixes($settings['thumbnailSizes']);
     }
     $this->setFilename($entity->get($field));
 }
Exemplo n.º 17
0
 protected function getFilteredPostsIds(array $identifiers, $mask, array $orX = [])
 {
     $orX = array_map(function ($value) {
         return str_replace('p.', 'Posts.', $value);
     }, $orX);
     $query = $this->Posts->find();
     $aclFilter = new CakephpOrmAclFilter($query);
     $aclFilter->setAclSchema($this->aclSchema);
     $aclFilter->apply('Posts', 'id', 'post-', $identifiers, $mask, $orX);
     $postsIds = [];
     foreach ($query->all() as $post) {
         $postsIds[] = $post->id;
     }
     return $postsIds;
 }
Exemplo n.º 18
0
 /**
  * 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->association('tags')->replaceLinks($article, $tags);
  * ```
  *
  * `$article->get('tags')` will contain only `[$tag1, $tag3]` at the end
  *
  * @param \Cake\Datasource\EntityInterface $sourceEntity an entity persisted in the source table for
  * this association
  * @param array $targetEntities list of entities from the target table to be linked
  * @param array $options list of options to be passed to the internal `save`/`delete` calls
  * when persisting/updating new links, or deleting existing ones
  * @throws \InvalidArgumentException if non persisted entities are passed or if
  * any of them is lacking a primary key value
  * @return bool success
  */
 public function replaceLinks(EntityInterface $sourceEntity, array $targetEntities, array $options = [])
 {
     $bindingKey = (array) $this->bindingKey();
     $primaryValue = $sourceEntity->extract($bindingKey);
     if (count(array_filter($primaryValue, 'strlen')) !== count($bindingKey)) {
         $message = 'Could not find primary key value for source entity';
         throw new InvalidArgumentException($message);
     }
     return $this->junction()->connection()->transactional(function () use($sourceEntity, $targetEntities, $primaryValue, $options) {
         $foreignKey = (array) $this->foreignKey();
         $hasMany = $this->source()->association($this->_junctionTable->alias());
         $existing = $hasMany->find('all')->where(array_combine($foreignKey, $primaryValue));
         $associationConditions = $this->conditions();
         if ($associationConditions) {
             $existing->contain($this->target()->alias());
             $existing->andWhere($associationConditions);
         }
         $jointEntities = $this->_collectJointEntities($sourceEntity, $targetEntities);
         $inserts = $this->_diffLinks($existing, $jointEntities, $targetEntities, $options);
         if ($inserts && !$this->_saveTarget($sourceEntity, $inserts, $options)) {
             return false;
         }
         $property = $this->property();
         if (count($inserts)) {
             $inserted = array_combine(array_keys($inserts), (array) $sourceEntity->get($property));
             $targetEntities = $inserted + $targetEntities;
         }
         ksort($targetEntities);
         $sourceEntity->set($property, array_values($targetEntities));
         $sourceEntity->dirty($property, false);
         return true;
     });
 }
Exemplo n.º 19
0
 /**
  * Initialize method
  *
  * @param array $config The configuration for the Table.
  * @return void
  */
 public function initialize(array $config)
 {
     parent::initialize($config);
     $this->table('balance');
     $this->displayField('id');
     $this->primaryKey('id');
 }
Exemplo n.º 20
0
 /**
  * Initialize method
  *
  * @param array $config The configuration for the Table.
  * @return void
  */
 public function initialize(array $config)
 {
     parent::initialize($config);
     $this->table('notification');
     $this->displayField('ID');
     $this->primaryKey('ID');
 }
Exemplo n.º 21
0
 /**
  * Initialize method
  *
  * @param array $config The configuration for the Table.
  * @return void
  */
 public function initialize(array $config)
 {
     parent::initialize($config);
     $this->table('deporte_actividad');
     $this->displayField('iddeporte');
     $this->primaryKey('iddeporte');
 }
Exemplo n.º 22
0
 /**
  * Initialize method
  *
  * @param array $config The configuration for the Table.
  * @return void
  */
 public function initialize(array $config)
 {
     parent::initialize($config);
     $this->table('categories');
     $this->displayField('CatName');
     $this->primaryKey('CatId');
 }
 /**
  * @param array $config Config
  * @return void
  */
 public function initialize(array $config)
 {
     $this->table('oauth_refresh_tokens');
     $this->primaryKey('refresh_token');
     $this->belongsTo('AccessTokens', ['className' => 'OAuthServer.AccessTokens', 'foreignKey' => 'oauth_token']);
     parent::initialize($config);
 }
Exemplo n.º 24
0
 /**
  * @param array $config Config
  * @return void
  */
 public function initialize(array $config)
 {
     $this->table('oauth_access_token_scopes');
     $this->belongsTo('AccessTokens', ['className' => 'OAuthServer.AccessTokens', 'foreignKey' => 'oauth_token']);
     $this->belongsTo('Scopes', ['className' => 'OAuthServer.Scopes']);
     parent::initialize($config);
 }
Exemplo n.º 25
0
 /**
  * Initialize method
  *
  * @param array $config The configuration for the Table.
  * @return void
  */
 public function initialize(array $config)
 {
     parent::initialize($config);
     $this->table('product_type');
     $this->displayField('name');
     $this->primaryKey('id');
 }
Exemplo n.º 26
0
 /**
  * Do some checks on the table which has been passed to make sure that it has what we need
  *
  * @param string $table The table
  * @return void
  */
 protected function checkTable($table)
 {
     try {
         $this->Table = $this->loadModel($table);
     } catch (Exception $e) {
         $this->out(__('<error>' . $e->getMessage() . '</error>'));
         exit;
     }
     if (get_class($this->Table) === 'AppModel') {
         $this->out(__('<error>The table could not be found, instance of AppModel loaded.</error>'));
         exit;
     }
     if (!$this->Table->hasBehavior('Proffer')) {
         $out = __("<error>The table '" . $this->Table->alias() . "' does not have the Proffer behavior attached.</error>");
         $this->out($out);
         exit;
     }
     $config = $this->Table->behaviors()->Proffer->config();
     foreach ($config as $field => $settings) {
         if (!$this->Table->hasField($field)) {
             $out = __("<error>The table '" . $this->Table->alias() . "' does not have the configured upload field in it's schema.</error>");
             $this->out($out);
             exit;
         }
         if (!$this->Table->hasField($settings['dir'])) {
             $out = __("<error>The table '" . $this->Table->alias() . "' does not have the configured dir field in it's schema.</error>");
             $this->out($out);
             exit;
         }
     }
 }
Exemplo n.º 27
0
 /**
  * @param \Cake\Database\Schema\Table $table Table schema
  * @return \Cake\Database\Schema\Table
  */
 protected function _initializeSchema(Schema $table)
 {
     $table->columnType('payload', 'serialize');
     $table->columnType('options', 'serialize');
     $table->columnType('history', 'json');
     return parent::_initializeSchema($table);
 }
 /**
  * Initialize method
  *
  * @param array $config The configuration for the Table.
  * @return void
  */
 public function initialize(array $config)
 {
     parent::initialize($config);
     $this->table('received_messages');
     $this->displayField('id');
     $this->primaryKey('id');
 }
Exemplo n.º 29
0
 /**
  * Initialize method
  *
  * @param array $config The configuration for the Table.
  * @return void
  */
 public function initialize(array $config)
 {
     parent::initialize($config);
     $this->table('headquarters');
     $this->displayField('name');
     $this->primaryKey('id');
 }
Exemplo n.º 30
-1
 /**
  * Toggle ajax field.
  *
  * @param Table $table
  * @param $id
  * @param $value
  * @param string $field
  */
 public function fieldToggle(Table $table, $id, $value, $field = 'status')
 {
     $this->_controller->serializeAjax = false;
     if (empty($id) || $value === null) {
         throw new Exception(__d('union', 'Invalid content'));
     }
     $this->_controller->viewBuilder()->layout('ajax')->templatePath('Common');
     $record = $table->get($id);
     $record->{$field} = (int) (!$value);
     if ($entity = $table->save($record)) {
         $this->_controller->set('record', $entity);
         $this->_controller->render('Union/Core.toggle');
     } else {
         throw new Exception(__d('union', 'Failed toggling field {0} to {1}', $field, $record->{$field}));
     }
 }