find() public method

{@inheritDoc}
See also: Cake\ORM\Table::find()
public find ( $finder, array $options = [] )
$options array
 /**
  * @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');
         }
     }
 }
 /**
  * Find Matches
  *
  * Assemble a query containing one or more MATCH() AGAINST() clauses
  * @param \Cake\ORM\Query $query Query to modify
  * @param array $options Options for the query
  * @throws SearchableException If keys 'match' or 'against' are not set
  * @throws SearchableException If columns are invalid
  * @return \Cake\ORM\Query
  */
 public function findMatches(Query $query, array $options)
 {
     $conditions = [];
     $options = array_values($options);
     //assemble MATCH() AGAINST() clauses
     foreach ($options as $key => $option) {
         if (!isset($option['match']) || !isset($option['against'])) {
             throw new SearchableException("Keys 'match' and 'against' must be set");
         }
         if ($this->_validateColumns($option['match'])) {
             $conditions[$key] = "MATCH({$option['match']}) AGAINST (:match{$key} ";
             if (isset($option['mode'])) {
                 if (in_array($option['mode'], $this->_modesWhitelist)) {
                     $conditions[$key] .= $option['mode'] . ' ';
                 }
             }
             $conditions[$key] .= ")";
         }
     }
     $query->find('all', ['conditions' => $conditions]);
     //bind params
     foreach ($options as $key => $option) {
         $query->bind(":match{$key}", $option['against']);
     }
     return $query;
 }
 /**
  * Find By Distance using spherical cosine law
  *
  * @param \Cake\ORM\Query $query Query to modify
  * @param array $options Options for the query
  * @throws GeoDistanceInvalidArgumentException If parameters are missing or invalid
  * @return \Cake\ORM\Query
  */
 public function findByDistance(Query $query, array $options)
 {
     // set up parameters
     $this->_validateOptions($options);
     $latitude = $options['latitude'];
     $longitude = $options['longitude'];
     $radius = $options['radius'];
     if (isset($options['units']) && !empty($options['units'])) {
         $units = $options['units'];
     } else {
         $units = $this->_config['units'];
     }
     $earthRadius = $this->_getEarthRadius($units);
     // construct query
     $sphericalCosineSql = "(:earth_radius * ACOS(\n            COS(RADIANS(:latitude)) *\n            COS(RADIANS({$this->_config['latitudeColumn']})) *\n            COS( RADIANS({$this->_config['longitudeColumn']}) - RADIANS(:longitude) ) +\n            SIN(RADIANS(:latitude)) *\n            SIN(RADIANS({$this->_config['latitudeColumn']}))\n        ) )";
     $connection = $query->connection();
     if ($connection->driver() instanceof Mysql) {
         $distance = "ROUND({$sphericalCosineSql}, 3)";
     } elseif ($connection->driver() instanceof Postgres) {
         $distance = "ROUND( CAST({$sphericalCosineSql} AS numeric), 3)";
     }
     $queryOptions = ['fields' => ['distance' => $distance], 'order' => ['distance ASC'], 'conditions' => ["{$distance} <= :radius"]];
     $query->find('all', $queryOptions)->autoFields(true)->bind(':earth_radius', $earthRadius, 'integer')->bind(':latitude', $latitude, 'float')->bind(':longitude', $longitude, 'float')->bind(':radius', $radius, 'float');
     return $query;
 }
 /**
  * Find all tasks grouped by project
  * 
  * @param Query $query
  * @param type $options
  * @return Query
  */
 public function findTasksByProject(Query $query, $options = [])
 {
     $options += ['where' => NULL];
     $query->find('list', ['groupField' => 'project_id']);
     $query->where($options['where']);
     return $query;
 }
Beispiel #5
0
 public function init()
 {
     parent::init();
     // 1. Not all fixtures want to use the dev db.
     if (is_null($this->tableName)) {
         return;
     }
     // 2. We need to do this to ensure that the tables really do use the connection to the
     // dev db.
     TableRegistry::remove($this->tableName);
     $table = TableRegistry::get($this->tableName, ['connection' => ConnectionManager::get('dev')]);
     //if(!is_null($this->joinTableName)) {
     //TableRegistry::remove($this->joinTableName);
     //$n=TableRegistry::get($this->joinTableName, ['connection' => ConnectionManager::get('fixture')]);
     //}
     // 3. Now build the query to retrieve the source records
     $query = new Query(ConnectionManager::get('dev'), $table);
     $query->find('all');
     //if(!is_null($this->order)) $query->order($this->order);
     //if(!is_null($this->joinTableName)) $query->leftJoin($this->joinTableName,'semesters.id = sections.semester_id');
     //$c=$query->count();
     // 4. Copy the records
     /* @var \Cake\ORM\Entity $record */
     foreach ($query as $record) {
         $this->records[] = $record->toArray();
     }
     // 5. Do this again to ensure that the table uses the 'test' connection.
     TableRegistry::remove($this->tableName);
     TableRegistry::get($this->tableName, ['connection' => ConnectionManager::get('test')]);
     //if(!is_null($this->joinTableName)) {
     //TableRegistry::remove($this->joinTableName);
     //TableRegistry::get($this->joinTableName, ['connection' => ConnectionManager::get('test')]);
     //}
 }
 /**
  * FindOptions method
  *
  * @param Query $query   query
  * @param array $options options
  *
  * @return array
  */
 public function findOptions(Query $query, array $options)
 {
     $typeMissions = $query->find('all')->toArray();
     $typeOptions = [];
     foreach ($typeMissions as $typeMission) {
         $typeOptions[$typeMission->id] = $typeMission->getName();
     }
     return $typeOptions;
 }
 /**
  * {@inheritdoc}
  *
  * @param \Cake\ORM\Query $query Query.
  * @param array $options Options.
  * @return \Cake\ORM\Query
  */
 public function findKv(Query $query, array $options)
 {
     return $query->find('list', ['keyField' => 'path', 'valueField' => 'value', 'groupField' => 'namespace'])->formatResults(function ($results) {
         $resultSet = $results->toArray();
         if (isset($resultSet[''])) {
             $resultSet += $resultSet[''];
             unset($resultSet['']);
         }
         return $resultSet;
     });
 }
 /**
  * Attaches comments to each entity on find operation.
  *
  * @param \Cake\Event\Event $event The event that was triggered
  * @param \Cake\ORM\Query $query The query object
  * @param array $options Additional options as an array
  * @param bool $primary Whether is find is a primary query or not
  * @return void
  */
 public function beforeFind(Event $event, $query, $options, $primary)
 {
     if ($this->_enabled && $query->count() > 0) {
         $pk = $this->_table->primaryKey();
         $tableAlias = Inflector::underscore($this->_table->alias());
         $query->contain(['Comments' => function ($query) {
             return $query->find('threaded')->contain(['Users'])->order($this->config('order'));
         }]);
         if ($this->config('count') || isset($options['comments_count']) && $options['comments_count'] === true) {
             $query->formatResults(function ($results) use($pk, $tableAlias) {
                 return $results->map(function ($entity) use($pk, $tableAlias) {
                     $entityId = $entity->{$pk};
                     $count = TableRegistry::get('Comment.Comments')->find()->where(['entity_id' => $entityId, 'table_alias' => $tableAlias])->count();
                     $entity->set('comments_count', $count);
                     return $entity;
                 });
             });
         }
     }
 }
 /**
  * Login and submit a PUT request to a $url that is expected to update
  * a given record. Then redirect to a given $redirect_url, read the updated record
  * from the $table and return it to the caller.
  *
  * @param int $user_id The user to login as.
  * @param String $url The url to send the request to.
  * @param array $post_data
  * @param String $redirect_url The url to redirect to, after the update.
  * @param \Cake\ORM\Table $table The table to receive the new record.
  * @return \Cake\ORM\Entity The newly added record, as read from the db.
  */
 protected function genericEditPutProlog($user_id, $url, $post_data, $redirect_url, $table)
 {
     $connection = ConnectionManager::get('test');
     $query = new Query($connection, $table);
     // Retrieve the record with the lowest id.
     $originalRecord = $query->find('all')->order(['id' => 'ASC'])->first();
     $edit_id = $originalRecord['id'];
     $this->fakeLogin($user_id);
     $this->put($url . '/' . $edit_id, $post_data);
     $this->assertResponseSuccess();
     // 2xx, 3xx
     $this->assertRedirect($redirect_url);
     // Now retrieve that 1 record and send it back.
     $query = new Query($connection, $table);
     return $query->find('all')->where(['id' => $edit_id])->first();
 }
 /**
  * Find all comments related to a specific content
  * @param string $ref Model linked with comments
  * @param int $ref_id ID of the content linked with the comments
  * @param array $options
  * @return \Cake\ORM\Query
  * @todo  Supprimer les commentaires inline : si le code est suffisamment clair cela se lit tout seul, sinon séparer en sous méthodes protected
  */
 public function findRelated(Query $query, array $options)
 {
     // We had the conditions to find linked comments only
     // We need to retrieve User information
     if (!isset($options['contain']['Users'])) {
         $select = Configure::read('Plugin.Comments.users');
         unset($select['className']);
         $select[] = 'Users.id';
         $select = array_values($select);
         $options['contain'][] = 'Users';
         $options['select'][] = $select;
         $options['select'] = current($options['select']);
     }
     if (Configure::read('Plugin.Comments.subcomments')) {
         $options['select'][] = 'Comments.parent_id';
         $comments = $query->find('threaded')->select($options['select'])->contain($options['contain']);
         return $comments;
     }
     $comments = $query->find('all')->select($options['select'])->contain($options['contain'])->orderDesc('Comments.id');
     return $comments;
 }
 /**
  * Formats entities to set hidden fields
  *
  * @param Event $event
  * @param Query $query
  * @return Query
  */
 public function beforeFind(Event $event, Query $query)
 {
     if (!$this->_buildAuthorization()) {
         return $query;
     }
     /**
      * Apply field visibility and accessibility
      */
     $notVisible = $this->_getNotVisibleFields();
     $query->formatResults(function ($results) use($notVisible) {
         return $results->map(function ($row) use($notVisible) {
             if (isset($row) && $row instanceof Entity) {
                 $row->hiddenProperties(array_merge($row->hiddenProperties(), $notVisible));
             }
             return $row;
         });
     });
     /**
      * Apply finders
      */
     $finders = array_diff($this->_getFinders(), $this->_getUnauthorizedFinders());
     foreach ($finders as $finder) {
         $query->find($finder);
     }
     return $query;
 }
Beispiel #12
0
 /**
  * Decrypts value after every find operation ONLY IF it was added to the
  * implemented events.
  *
  * @param \Cake\Event\Event $event Event.
  * @param \Cake\ORM\Query $query Query.
  * @param \ArrayObject $options Options.
  * @param bool $primary Whether or not this is the root query or an associated query.
  * @return void
  */
 public function beforeFind(Event $event, Query $query, ArrayObject $options, $primary)
 {
     $query->find('decrypted');
 }
 /**
  * Allows you to do a $table->find('sluggedList') and get an array of [slug]=>name instead of id=>name
  * @param Query $query
  * @param array $options
  * @return Query
  */
 public function findSluggedList(Query $query, array $options)
 {
     $config = $this->config();
     return $query->find('list', ['keyField' => $config['field']]);
 }
 public function findFemaleRatio(Query $query, $options = [])
 {
     $allManagers = $this->find()->select($query->func()->count('*'));
     return $query->find('female')->select(['female_ratio' => $query->newExpr($query->func()->count('*'))->add($allManagers)->type('/')]);
 }
 public function findInRegionalGroups(Query $query)
 {
     $query->find('inContinentGroups')->formatResults(function ($results) {
         return $results->map(function ($continent) {
             return collection($continent)->groupBy('region');
         });
     });
     return $query;
 }
 public function findVencido(Query $query, array $options)
 {
     return $query->find('pago')->where(['vencimento <' => $query->func()->now()]);
 }