fetchAllAssoc example

// Check insert. Add one value too many.     $values = [];
    for ($delta = 0; $delta <= $this->fieldCardinality; $delta++) {
      $values[$delta]['value'] = mt_rand(1, 127);
    }
    $entity->{$this->fieldName} = $values;
    $entity->save();

    $connection = Database::getConnection();
    // Read the tables and check the correct values have been stored.     $rows = $connection->select($this->table, 't')->fields('t')->execute()->fetchAllAssoc('delta', \PDO::FETCH_ASSOC);
    $this->assertCount($this->fieldCardinality, $rows);
    foreach ($rows as $delta => $row) {
      $expected = [
        'bundle' => $bundle,
        'deleted' => 0,
        'entity_id' => $entity->id(),
        'revision_id' => $entity->getRevisionId(),
        'langcode' => $entity->language()->getId(),
        'delta' => $delta,
        $this->fieldName . '_value' => $values[$delta]['value'],
      ];
      
    $node->isDefaultRevision(TRUE);
    $node->save();

    $taxonomy_index = $this->getTaxonomyIndex();
    $this->assertEquals($term->id()$taxonomy_index[$node->id()]->tid);
  }

  protected function getTaxonomyIndex() {
    return \Drupal::database()->select('taxonomy_index')
      ->fields('taxonomy_index')
      ->execute()
      ->fetchAllAssoc('nid');
  }

}


    // This array acts as a placeholder for the data selected later     // while keeping the correct order.     $tracker_data = $query
      ->addTag('node_access')
      ->fields('t', ['nid', 'changed'])
      ->condition('t.published', 1)
      ->orderBy('t.changed', 'DESC')
      ->limit(25)
      ->execute()
      ->fetchAllAssoc('nid');

    $cacheable_metadata = new CacheableMetadata();
    $rows = [];
    if (!empty($tracker_data)) {
      // Load nodes into an array with the same order as $tracker_data.       /** @var \Drupal\node\NodeInterface[] $nodes */
      $nodes = $this->nodeStorage->loadMultiple(array_keys($tracker_data));

      // Enrich the node data.       $result = $this->commentStatistics->read($nodes, 'node', FALSE);
      foreach ($result as $statistics) {
        
$this->catchException($e);
      return FALSE;
    }
  }

  /** * {@inheritdoc} */
  public function getMultiple(array $keys) {
    $values = [];
    try {
      $result = $this->connection->query('SELECT [name], [value] FROM {' . $this->connection->escapeTable($this->table) . '} WHERE [name] IN ( :keys[] ) AND [collection] = :collection', [':keys[]' => $keys, ':collection' => $this->collection])->fetchAllAssoc('name');
      foreach ($keys as $key) {
        if (isset($result[$key])) {
          $values[$key] = $this->serializer->decode($result[$key]->value);
        }
      }
    }
    catch (\Exception $e) {
      // @todo: Perhaps if the database is never going to be available,       // key/value requests should return FALSE in order to allow exception       // handling to occur but for now, keep it an array, always.     }
    
// No access for all languages as the non language aware node access module     // denies access.     $this->assertNodeAccess($expected_node_access_no_access$this->nodes['private_no_language_public']$this->webUser);

    // Query the node table with the node access tag in several languages.     $connection = Database::getConnection();
    // Query with no language specified. The fallback (hu or und) will be used.     $select = $connection->select('node', 'n')
      ->fields('n', ['nid'])
      ->addMetaData('account', $this->webUser)
      ->addTag('node_access');
    $nids = $select->execute()->fetchAllAssoc('nid');

    // Four nodes should be returned with public Hungarian translations or the     // no language public node.     $this->assertCount(4, $nids, 'Query returns 4 nodes when no langcode is specified.');
    $this->assertArrayHasKey($this->nodes['public_both_public']->id()$nids);
    $this->assertArrayHasKey($this->nodes['public_ca_private']->id()$nids);
    $this->assertArrayHasKey($this->nodes['private_both_public']->id()$nids);
    $this->assertArrayHasKey($this->nodes['public_no_language_public']->id()$nids);

    // Query with Hungarian (hu) specified.     $select = $connection->select('node', 'n')
      
$this->connection->query('ALTER TABLE {' . $table . '} DROP PRIMARY KEY');
    return TRUE;
  }

  /** * {@inheritdoc} */
  protected function findPrimaryKeyColumns($table) {
    if (!$this->tableExists($table)) {
      return FALSE;
    }
    $result = $this->connection->query("SHOW KEYS FROM {" . $table . "} WHERE Key_name = 'PRIMARY'")->fetchAllAssoc('Column_name');
    return array_keys($result);
  }

  /** * {@inheritdoc} */
  public function addUniqueKey($table$name$fields) {
    if (!$this->tableExists($table)) {
      throw new SchemaObjectDoesNotExistException("Cannot add unique key '$name' to table '$table': table doesn't exist.");
    }
    if ($this->indexExists($table$name)) {
      
$i = 1;
    foreach ($data as $datum) {
      $this->executable->sourceIdValues = ['id' => $i++];

      // Test the input value is not altered.       $new_value = $this->logPlugin->transform($datum['value']$this->executable, new Row(), 'foo');
      $this->assertSame($datum['value']$new_value);

      // Test the stored message.       $message = $this->executable->getIdMap()
        ->getMessages($this->executable->sourceIdValues)
        ->fetchAllAssoc('message');
      $actual_message = key($message);
      $this->assertSame($datum['expected_message']$actual_message);
    }
  }

}

/** * MigrateExecutable test class. */
class TestMigrateExecutable extends MigrateExecutable {

  
return $this->connection->delete('book')
      ->condition('nid', $nid)
      ->execute();
  }

  /** * {@inheritdoc} */
  public function loadBookChildren($pid) {
    return $this->connection
      ->query("SELECT * FROM {book} WHERE [pid] = :pid", [':pid' => $pid])
      ->fetchAllAssoc('nid', \PDO::FETCH_ASSOC);
  }

  /** * {@inheritdoc} */
  public function getBookMenuTree($bid$parameters$min_depth$max_depth) {
    $query = $this->connection->select('book');
    $query->fields('book');
    for ($i = 1; $i <= $max_depth$i++) {
      $query->orderBy('p' . $i, 'ASC');
    }
    
"job" => "Singer",
      ],
      "Drummer" => [
        "id" => "3",
        "name" => "Ringo",
        "age" => "28",
        "job" => "Drummer",
      ],
    ];

    $statement = $this->connection->query('SELECT * FROM {test} WHERE [age] > :age', [':age' => 26]);
    $result = $statement->fetchAllAssoc('job', \PDO::FETCH_ASSOC);
    $this->assertSame($expected_result$result);

    $statement = $this->connection->query('SELECT * FROM {test} WHERE [age] > :age', [':age' => 26]);
    $result = $statement->fetchAllAssoc('job', \PDO::FETCH_OBJ);
    $this->assertEquals((object) $expected_result['Singer']$result['Singer']);
    $this->assertEquals((object) $expected_result['Drummer']$result['Drummer']);
  }

  /** * Tests ::fetchField(). */
  
->fields('ud')
      ->condition('module', $module);
    if (isset($uid)) {
      $query->condition('uid', $uid);
    }
    if (isset($name)) {
      $query->condition('name', $name);
    }
    $result = $query->execute();
    // If $module, $uid, and $name were passed, return the value.     if (isset($name) && isset($uid)) {
      $result = $result->fetchAllAssoc('uid');
      if (isset($result[$uid])) {
        return $result[$uid]->serialized ? unserialize($result[$uid]->value) : $result[$uid]->value;
      }
      return NULL;
    }
    $return = [];
    // If $module and $uid were passed, return data keyed by name.     if (isset($uid)) {
      foreach ($result as $record) {
        $return[$record->name] = ($record->serialized ? unserialize($record->value) : $record->value);
      }
      

  public function loadByProperties(array $properties) {
    $query = $this->connection->select($this->table, NULL, $this->options);
    $query->fields($this->table, $this->definitionFields());
    foreach ($properties as $name => $value) {
      if (!in_array($name$this->definitionFields(), TRUE)) {
        $fields = implode(', ', $this->definitionFields());
        throw new \InvalidArgumentException("An invalid property name, $name was specified. Allowed property names are: $fields.");
      }
      $query->condition($name$value);
    }
    $loaded = $this->safeExecuteSelect($query)->fetchAllAssoc('id', \PDO::FETCH_ASSOC);
    foreach ($loaded as $id => $link) {
      $loaded[$id] = $this->prepareLink($link);
    }
    return $loaded;
  }

  /** * {@inheritdoc} */
  public function loadByRoute($route_name, array $route_parameters = []$menu_name = NULL) {
    // Sort the route parameters so that the query string will be the same.
// Get the vid for each allowed value for taxonomy term reference fields     // which is used in a migration_lookup in the process pipeline.     if ($row->getSourceProperty('type') == 'taxonomy_term_reference') {
      $vocabulary = [];
      $data = unserialize($field_definition['data']);
      foreach ($data['settings']['allowed_values'] as $allowed_value) {
        $vocabulary[] = $allowed_value['vocabulary'];
      }
      $query = $this->select('taxonomy_vocabulary', 'v')
        ->fields('v', ['vid'])
        ->condition('machine_name', $vocabulary, 'IN');
      $allowed_vid = $query->execute()->fetchAllAssoc('vid');
      $row->setSourceProperty('allowed_vid', $allowed_vid);

      // If there is an i18n_mode use it to determine if this field is       // translatable. It is TRUE for i18n_modes 'Vocab Fixed' and 'Translate',       // for all others it is FALSE. When there is a term reference field with       // two vocabularies where one vocabulary is translatable and other is not       // the field itself is set to not translatable. Note mode '5' is not used       // for taxonomy but is listed here for completeness.       // - 0: No multilingual options.       // - 1: Localize. Localizable object.       // - 2: Fixed Language.
/** * {@inheritdoc} */
  public function prepareRow(Row $row) {
    // Find filters for this format.     $filters = $this->select('filter', 'f')
      ->fields('f')
      ->condition('format', $row->getSourceProperty('format'))
      ->condition('status', 1)
      ->execute()
      ->fetchAllAssoc('name');

    foreach ($filters as $id => $filter) {
      $filters[$id]['settings'] = unserialize($filter['settings']);
    }
    $row->setSourceProperty('filters', $filters);

    return parent::prepareRow($row);
  }

  /** * {@inheritdoc} */
$file_usage = $this->container->get('file.usage');
    $file_usage->add($file, 'testing', 'foo', 1);
    // Add the file twice to ensure that the count is incremented rather than     // creating additional records.     $file_usage->add($file, 'testing', 'bar', 2);
    $file_usage->add($file, 'testing', 'bar', 2);

    $usage = Database::getConnection()->select('file_usage', 'f')
      ->fields('f')
      ->condition('f.fid', $file->id())
      ->execute()
      ->fetchAllAssoc('id');
    $this->assertCount(2, $usage, 'Created two records');
    $this->assertEquals('testing', $usage[1]->module, 'Correct module');
    $this->assertEquals('testing', $usage[2]->module, 'Correct module');
    $this->assertEquals('foo', $usage[1]->type, 'Correct type');
    $this->assertEquals('bar', $usage[2]->type, 'Correct type');
    $this->assertEquals(1, $usage[1]->count, 'Correct count');
    $this->assertEquals(2, $usage[2]->count, 'Correct count');
  }

  /** * Tests file usage deletion when files are made temporary. */
$query->join('comment_entity_statistics', 'ces', "[n].[nid] = [ces].[entity_id] AND [ces].[field_name] = 'comment_forum' AND [ces].[entity_type] = 'node'");
      $query->join('forum', 'f', '[n].[vid] = [f].[vid]');
      $query->addExpression('COUNT([n].[nid])', 'topic_count');
      $query->addExpression('SUM([ces].[comment_count])', 'comment_count');
      $this->forumStatistics = $query
        ->fields('f', ['tid'])
        ->condition('n.status', 1)
        ->condition('n.default_langcode', 1)
        ->groupBy('tid')
        ->addTag('node_access')
        ->execute()
        ->fetchAllAssoc('tid');
    }

    if (!empty($this->forumStatistics[$tid])) {
      return $this->forumStatistics[$tid];
    }
  }

  /** * {@inheritdoc} */
  public function getChildren($vid$tid) {
    
Home | Imprint | This part of the site doesn't use cookies.