/** * converts a query Object into a flat table * properties are filed in first row * * @param Query $query * @return array */ public function prepareTableData(Query $query = null) { /* first row contains properties */ $data = [array_keys($query->first()->toArray())]; /** add data of an entity a row */ foreach ($query as $entity) { $data[] = array_values($entity->toArray()); } return $data; }
/** * Tests that first can be called against a query with a mapReduce * * @return void */ public function testFirstMapReduce() { $map = function ($row, $key, $mapReduce) { $mapReduce->emitIntermediate($row['id'], 'id'); }; $reduce = function ($values, $key, $mapReduce) { $mapReduce->emit(array_sum($values)); }; $table = TableRegistry::get('articles', ['table' => 'articles']); $query = new Query($this->connection, $table); $query->select(['id'])->hydrate(false)->mapReduce($map, $reduce); $first = $query->first(); $this->assertEquals(1, $first); }
/** * Custom finder for hashids field. * * Options: * - hid (required), best to use HashidBehavior::HID constant * - noFirst (optional, to leave the query open for adjustments, no first() called) * * @param \Cake\ORM\Query $query Query. * @param array $options Array of options as described above * @return \Cake\ORM\Query */ public function findHashed(Query $query, array $options) { $field = $this->_config['field']; if (!$field) { return $query; } $idField = $this->_primaryKey; $query->formatResults(function ($results) use($field, $idField) { $newResult = []; $results->each(function ($row, $key) use($field, $idField, &$newResult) { if (!empty($row[$idField])) { $row[$field] = $this->encodeId($row[$idField]); if ($row instanceof Entity) { $row->dirty($field, false); } $newResult[] = $row; } elseif (is_string($row)) { $newResult[$this->encodeId($key)] = $row; } }); return new Collection($newResult); }); if (!empty($options[static::HID])) { $id = $this->decodeHashid($options[static::HID]); $query->where([$idField => $id]); } $first = $this->_config['findFirst'] === true ? 'first' : $this->_config['findFirst']; if (!$first || !empty($options['noFirst'])) { return $query; } return $query->first(); }