本文整理汇总了PHP中Cake\ORM\Table::find方法的典型用法代码示例。如果您正苦于以下问题:PHP Table::find方法的具体用法?PHP Table::find怎么用?PHP Table::find使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Cake\ORM\Table
的用法示例。
在下文中一共展示了Table::find方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: entityGenerator
/**
* Helper generator for use with importTable().
*
* Yields a single new Entity instance approciate for $Table for each
* of $records where the values are merged with $defaults.
*
* Will skip any records that fail to validate, dumping validation
* errors to the console in the process.
*
* Used by imporTables().
*
* @param Cake\ORM\Table $Table A Table instance to save records into.
* @param array $records An array of Entity records to save into the Table.
* @param array $defaults Optional array of default field values to merge into each record.
* @param array $options Optional array of newEntity() options to use.
* @return void
*/
public function entityGenerator(Table $Table, array $records, array $defaults = [], array $options = [])
{
$defaultOptions = ['validate' => true, 'accessibleFields' => ['*' => true]];
$options = $options + $defaultOptions;
$keyField = $Table->primaryKey();
foreach ($records as $r) {
$r = Hash::merge($defaults, $r);
$id = !empty($r[$keyField]) ? $r[$keyField] : false;
if ($id) {
$entity = $Table->find()->where([$keyField => $id])->first();
if ($entity) {
$entity = $Table->patchEntity($entity, $r, $options);
if (!$entity->dirty()) {
$this->verbose("<success>{$Table->alias()} ({$id}): No changes.</success>");
continue;
}
} else {
$entity = $Table->newEntity($r, $options);
$entity->isNew(true);
}
} else {
$entity = $Table->newEntity($r, $options);
}
$errors = $entity->errors();
if ($errors) {
$this->printValidationErrors($Table->alias(), $id, $errors);
continue;
}
(yield $entity);
}
}
示例2: testUnaryExpression
/**
* 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);
}
示例3: read
/**
* Method used to read from a database session.
*
* @param int|string $id The key of the value to read
* @return mixed The value of the key or false if it does not exist
*/
public function read($id)
{
$result = $this->_table->find('all')->select(['data'])->where([$this->_table->primaryKey() => $id])->hydrate(false)->first();
if (empty($result)) {
return false;
}
return $result['data'];
}
示例4: listCronsAction
public function listCronsAction()
{
$cronSettings = $this->cronSettings->find()->hydrate(false)->toArray();
if (empty($cronSettings)) {
$cronSettings = ['output' => 'cron-all.log', 'recipients' => $this->site['sender']];
$this->cronSettings->save($this->cronSettings->newEntity()->set($cronSettings));
}
echo $this->twig->render('cron/list.twig', ['crons' => $this->cronsTable->find()->hydrate(false)->toArray(), 'cronSettings' => $this->cronSettings->find()->hydrate(false)->toArray()[0]]);
}
示例5: testFindListHydrated
/**
* Tests find('list') with hydrated records
*
* @return void
*/
public function testFindListHydrated()
{
$table = new Table(['table' => 'users', 'connection' => $this->connection]);
$table->displayField('username');
$query = $table->find('list', ['fields' => ['id', 'username']])->order('id');
$expected = [1 => 'mariano', 2 => 'nate', 3 => 'larry', 4 => 'garrett'];
$this->assertSame($expected, $query->toArray());
$query = $table->find('list', ['groupField' => 'odd'])->select(['id', 'username', 'odd' => new FunctionExpression('MOD', [new IdentifierExpression('id'), 2])])->hydrate(true)->order('id');
$expected = [1 => [1 => 'mariano', 3 => 'larry'], 0 => [2 => 'nate', 4 => 'garrett']];
$this->assertSame($expected, $query->toArray());
}
示例6: __setForLayout
/**
* 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);
}
示例7: read
/**
* Method used to read from a database session.
*
* @param int|string $id The key of the value to read
* @return string The value of the key or empty if it does not exist
*/
public function read($id)
{
$result = $this->_table->find('all')->select(['data'])->where([$this->_table->primaryKey() => $id])->hydrate(false)->first();
if (empty($result)) {
return '';
}
if (is_string($result['data'])) {
return $result['data'];
}
$session = stream_get_contents($result['data']);
if ($session === false) {
return '';
}
return $session;
}
示例8: getFilteredPostsIds
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;
}
示例9: testFind
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);
}
}
示例10: _getQuery
/**
* Builds a query for loading the passed list of entity objects along with the
* associations specified in $contain.
*
* @param Cake\Collection\CollectionInterface $objects The original entitites
* @param array $contain The associations to be loaded
* @param Cake\ORM\Table $source The table to use for fetching the top level entities
* @return Cake\ORM\Query
*/
protected function _getQuery($objects, $contain, $source)
{
$primaryKey = $source->primaryKey();
$method = is_string($primaryKey) ? 'get' : 'extract';
$keys = $objects->map(function ($entity) use($primaryKey, $method) {
return $entity->{$method}($primaryKey);
});
$query = $source->find()->select((array) $primaryKey)->where(function ($exp, $q) use($primaryKey, $keys, $source) {
if (is_array($primaryKey) && count($primaryKey) === 1) {
$primaryKey = current($primaryKey);
}
if (is_string($primaryKey)) {
return $exp->in($source->aliasField($primaryKey), $keys->toList());
}
$types = array_intersect_key($q->defaultTypes(), array_flip($primaryKey));
$primaryKey = array_map([$source, 'aliasField'], $primaryKey);
return new TupleComparison($primaryKey, $keys->toList(), $types, 'IN');
})->contain($contain);
foreach ($query->eagerLoader()->attachableAssociations($source) as $loadable) {
$config = $loadable->config();
$config['includeFields'] = true;
$loadable->config($config);
}
return $query;
}
示例11: beforeSave
/**
* Modifies the entity before it is saved so that translated fields are persisted
* in the database too.
*
* @param \Cake\Event\Event $event The beforeSave event that was fired
* @param \Cake\Datasource\EntityInterface $entity The entity that is going to be saved
* @param \ArrayObject $options the options passed to the save method
* @return void
*/
public function beforeSave(Event $event, EntityInterface $entity, ArrayObject $options)
{
$locale = $entity->get('_locale') ?: $this->locale();
$newOptions = [$this->_translationTable->alias() => ['validate' => false]];
$options['associated'] = $newOptions + $options['associated'];
$this->_bundleTranslatedFields($entity);
$bundled = $entity->get('_i18n') ?: [];
if ($locale === $this->config('defaultLocale')) {
return;
}
$values = $entity->extract($this->_config['fields'], true);
$fields = array_keys($values);
$primaryKey = (array) $this->_table->primaryKey();
$key = $entity->get(current($primaryKey));
$model = $this->_config['referenceName'];
$preexistent = $this->_translationTable->find()->select(['id', 'field'])->where(['field IN' => $fields, 'locale' => $locale, 'foreign_key' => $key, 'model' => $model])->bufferResults(false)->indexBy('field');
$modified = [];
foreach ($preexistent as $field => $translation) {
$translation->set('content', $values[$field]);
$modified[$field] = $translation;
}
$new = array_diff_key($values, $modified);
foreach ($new as $field => $content) {
$new[$field] = new Entity(compact('locale', 'field', 'content', 'model'), ['useSetters' => false, 'markNew' => true]);
}
$entity->set('_i18n', array_merge($bundled, array_values($modified + $new)));
$entity->set('_locale', $locale, ['setter' => false]);
$entity->dirty('_locale', false);
foreach ($fields as $field) {
$entity->dirty($field, false);
}
}
示例12: resetSlugs
/**
* ResetSlugs method.
*
* Regenerate all slugs. On large dbs this can take more than 30 seconds - a time
* limit is set to allow a minimum 100 updates per second as a preventative measure.
*
* Note that you should use the Reset behavior if you need additional functionality such
* as callbacks or timeouts.
*
* @param array $params
* @return bool Success
*/
public function resetSlugs($params = [])
{
if (!$this->_table->hasField($this->_config['field'])) {
throw new Exception('Table does not have field ' . $this->_config['field']);
}
$defaults = ['page' => 1, 'limit' => 100, 'fields' => array_merge([$this->_table->primaryKey()], $this->_config['label']), 'order' => $this->_table->displayField() . ' ASC', 'conditions' => $this->_config['scope'], 'overwrite' => true];
$params = array_merge($defaults, $params);
$count = $this->_table->find('all', compact('conditions'))->count();
$max = ini_get('max_execution_time');
if ($max) {
set_time_limit(max($max, $count / 100));
}
$this->_table->behaviors()->Slugged->config($params, null, false);
while ($records = $this->_table->find('all', $params)->toArray()) {
foreach ($records as $record) {
$record->isNew(true);
$options = ['validate' => true, 'fieldList' => array_merge([$this->_table->primaryKey(), $this->_config['field']], $this->_config['label'])];
if (!$this->_table->save($record, $options)) {
throw new Exception(print_r($this->_table->errors(), true));
}
}
$params['page']++;
}
return true;
}
示例13: testGenerateProductive
/**
* TreeHelperTest::testGenerateProductive()
*
* @return void
*/
public function testGenerateProductive()
{
$tree = $this->Table->find('threaded')->toArray();
$output = $this->Tree->generate($tree, ['indent' => false]);
$expected = '<ul><li>One<ul><li>One-SubA</li></ul></li><li>Two<ul><li>Two-SubA<ul><li>Two-SubA-1<ul><li>Two-SubA-1-1</li></ul></li></ul></li></ul></li><li>Three</li><li>Four<ul><li>Four-SubA</li></ul></li></ul>';
$this->assertTextEquals($expected, $output);
}
示例14: testGET_index
public function testGET_index()
{
// 1. Submit submit request, examine response, observe no redirect, and parse the response.
$book_id = FixtureConstants::bookTypical;
$book = $this->Books->get($book_id);
$this->get('/books/' . $book_id . '/transactions');
$this->assertResponseCode(200);
$this->assertNoRedirect();
$dom = new \DomDocument();
$dom->loadHTML($this->_response->body());
$xpath = new \DomXPath($dom);
// 2. Isolate the content produced by this controller method (excluding the layout.)
$content_node = $this->getTheOnlyOne($xpath, "//div[@id='TransactionsIndex']");
// 3. Count the A tags.
$unknownATagCnt = $xpath->query(".//a", $content_node)->length;
// 4. Look for the create new transaction link
$this->getTheOnlyOne($xpath, "//a[@id='TransactionNewform']", $content_node);
$unknownATagCnt--;
// 5. Ensure that there is a suitably named table to display the results.
$table_node = $this->getTheOnlyOne($xpath, "//table[@id='TransactionsTable']", $content_node);
// 6. Now inspect the caption of the table.
$this->assertContains($book['title'], $this->getTheOnlyOne($xpath, "caption", $table_node)->textContent);
// 7. Ensure that said table's thead element contains the correct
// headings, in the correct order, and nothing else.
$column_header_nodes = $xpath->query("thead/tr/th", $table_node);
$this->assertEquals($column_header_nodes->length, 3);
// no other columns
$this->getTheOnlyOne($xpath, "thead/tr/th[1][@id='note']", $table_node);
$this->getTheOnlyOne($xpath, "thead/tr/th[2][@id='tran_datetime']", $table_node);
$this->getTheOnlyOne($xpath, "thead/tr/th[3][@id='actions']", $table_node);
// 8. Ensure that the tbody section has the correct quantity of rows.
$dbRecords = $this->Transactions->find()->where(['book_id' => $book_id])->order(['tran_datetime' => 'desc']);
$tbody_nodes = $xpath->query("tbody/tr", $table_node);
$this->assertTrue($tbody_nodes->length == $dbRecords->count());
// 9. Ensure that the values displayed in each row, match the values from
// the fixture. The values should be presented in a particular order
// with nothing else thereafter.
$iterator = new \MultipleIterator();
$iterator->attachIterator(new \ArrayIterator($dbRecords->execute()->fetchAll('assoc')));
$iterator->attachIterator(new \ArrayIterator(iterator_to_array($tbody_nodes)));
foreach ($iterator as $values) {
$fixtureRecord = $values[0];
$row_node = $values[1];
$column_nodes = $xpath->query("td", $row_node);
$this->assertEquals($fixtureRecord['Transactions__note'], $column_nodes->item(0)->textContent);
//$this->assertEquals($fixtureRecord['Transactions__datetime'], $column_nodes->item(1)->textContent);
// 9.1 Now examine the action links
$action_nodes = $xpath->query("a", $column_nodes->item(2));
$this->assertTrue($action_nodes->length == 2);
$this->getTheOnlyOne($xpath, "a[@name='TransactionView']", $column_nodes->item(2));
$unknownATagCnt--;
$this->getTheOnlyOne($xpath, "a[@name='TransactionEditform']", $column_nodes->item(2));
$unknownATagCnt--;
// 9.9 No other columns
$this->assertEquals($column_nodes->length, $column_header_nodes->length);
}
// 10. Ensure that all the <A> tags have been accounted for
$this->assertEquals(0, $unknownATagCnt);
}
示例15: find
/**
* Overload find to cause issues.
*
* @param string $type Find type
* @param array $options find options
* @return object
*/
public function find($type = 'all', $options = [])
{
if (empty($options['conditions'])) {
$options['conditions'] = [];
}
$options['conditions'] = array_merge($options['conditions'], ['Comments.published' => 'Y']);
return parent::find($type, $options);
}