orderBy example

/** * Event listener function of the library store. * * @return void */
    public function libraryAction()
    {
        $builder = $this->get('models')->createQueryBuilder();
        $builder->select(['components', 'fields'])
            ->from(Component::class, 'components')
            ->leftJoin('components.fields', 'fields')
            ->orderBy('components.id', 'ASC')
            ->addOrderBy('fields.position', 'ASC');

        $components = $builder->getQuery()->getArrayResult();

        $snippets = $this->get('snippets')->getNamespace('backend/emotion/view/detail');
        foreach ($components as &$component) {
            $name = str_replace(' ', '_', strtolower($component['name']));

            $component['fieldLabel'] = $snippets->get($name$component['name']);
        }
        unset($component);

        
'role.name as groupname',
            'user.active as active',
            'user.email as email',
        ]);
        $builder->from(User::class, 'user');
        $builder->join('user.role', 'role');
        if (!empty($filter)) {
            $builder->where('user.username LIKE ?1')
                    ->orWhere('user.name LIKE ?1')
                    ->setParameter(1, '%' . $filter . '%');
        }
        $builder->orderBy('username');

        return $builder;
    }

    /** * Returns an instance of the \Doctrine\ORM\Query object which select a list of roles. * * @param int|null $offset * @param int|null $limit * * @return Query<Role> */
'emotion.valid_from',
                'emotion.valid_to',
                'emotion.customer_stream_ids',
                'emotion.replacement',
                'now()',
            ])
            ->from('s_emotion', 'emotion')
            ->andWhere('emotion.active = 1')
            ->andWhere('emotion.is_landingpage = 1')
            ->andWhere('(emotion.valid_from IS NULL OR emotion.valid_from <= now())')
            ->andWhere('(emotion.valid_to IS NULL OR emotion.valid_to >= now())')
            ->orderBy('emotion.position', 'ASC')
            ->addOrderBy('emotion.id', 'ASC');
    }

    /** * Get QueryBuilder for shops of an emotion. */
    private function getLandingPageShopsQuery(): QueryBuilder
    {
        return $this->connection->createQueryBuilder()
            ->select(['shops.shop_id'])
            ->from('s_emotion_shops', 'shops')
            

  protected $isPublic;

  /** * {@inheritdoc} */
  public function query() {
    return $this->select('files', 'f')
      ->fields('f')
      ->condition('f.filepath', '/tmp%', 'NOT LIKE')
      ->orderBy('f.timestamp')
      // If two or more files have the same timestamp, they'll end up in a       // non-deterministic order. Ordering by fid (or any other unique field)       // will prevent this.       ->orderBy('f.fid');
  }

  /** * {@inheritdoc} */
  protected function initializeIterator() {
    $site_path = $this->configuration['site_path'] ?? 'sites/default';
    
$query = new QueryBuilder($this->connection);
        $query->select([
            str_replace(
                array_keys($params),
                array_values($params),
                '@n:=IF(@c=#table#.#source_column#, @n+1, IF(@c:=#table#.#source_column#,1,1)) as id_count'
            ),
            $table . '.' . $referenceColumn,
            $table . '.' . $sourceColumn,
        ]);
        $query->from($table$table);
        $query->orderBy($table . '.' . $sourceColumn);

        return $query;
    }

    private function buildOneToManyPropertyAccessor(EntityDefinition $definition, OneToManyAssociationField $association): string
    {
        $reference = $association->getReferenceDefinition();

        if ($association instanceof ChildrenAssociationField) {
            return $reference->getEntityName() . '.parentId';
        }

        
'revision_id' => '2',
        'langcode' => 'ro',
        'delta' => '0',
        'new_base_field_value' => 'foo-ro',
      ];
    }

    // Check that the deleted field's data is preserved in the dedicated     // 'deleted' table.     $result = $this->database->select($dedicated_deleted_table_name, 't')
      ->fields('t')
      ->orderBy('revision_id', 'ASC')
      ->orderBy('langcode', 'ASC')
      ->execute()
      ->fetchAll(\PDO::FETCH_ASSOC);
    $this->assertSameSize($expected$result);

    // Use assertEquals and not assertSame here to prevent that a different     // sequence of the columns in the table will affect the check.     $this->assertEquals($expected$result);

    if ($create_entity_revision) {
      $dedicated_deleted_revision_table_name = $table_mapping->getDedicatedRevisionTableName($storage_definition, TRUE);
      
return self::NAME;
    }

    /** * {@inheritdoc} */
    public function getUrls(Context $context$limit = null, $offset = null)
    {
        $qb = $this->getBaseQuery()
            ->addSelect(['id', 'link'])
            ->setParameter(':shop', $context->getShopId())
            ->orderBy('id');

        if ($limit !== null && $offset !== null) {
            $qb->setFirstResult($offset)
                ->setMaxResults($limit);
        }

        $result = $qb->execute()->fetchAll();

        if (!\count($result)) {
            return [];
        }

        

  public function __construct(Connection $connection$table$alias = NULL, array $options = []) {
    // @todo Remove the __construct in Drupal 11.     // @see https://www.drupal.org/project/drupal/issues/3256524     parent::__construct($connection$table$alias$options);
    unset($this->queryOptions['return']);
  }

  public function orderRandom() {
    $alias = $this->addExpression('RANDOM()', 'random_field');
    $this->orderBy($alias);
    return $this;
  }

  /** * Overrides SelectQuery::orderBy(). * * PostgreSQL adheres strictly to the SQL-92 standard and requires that when * using DISTINCT or GROUP BY conditions, fields and expressions that are * ordered on also need to be selected. This is a best effort implementation * to handle the cases that can be automated by adding the field if it is not * yet selected. * * @code * $query = \Drupal::database()->select('example', 'e'); * $query->join('example_revision', 'er', '[e].[vid] = [er].[vid]'); * $query * ->distinct() * ->fields('e') * ->orderBy('timestamp'); * @endcode * * In this query, it is not possible (without relying on the schema) to know * whether timestamp belongs to example_revision and needs to be added or * belongs to node and is already selected. Queries like this will need to be * corrected in the original query by adding an explicit call to * SelectQuery::addField() or SelectQuery::fields(). * * Since this has a small performance impact, both by the additional * processing in this function and in the database that needs to return the * additional fields, this is done as an override instead of implementing it * directly in SelectQuery::orderBy(). */
$builder = $this->builder();

        if ($this->tempUseSoftDeletes) {
            $builder->where($this->table . '.' . $this->deletedField, null);
        } elseif ($this->useSoftDeletes && empty($builder->QBGroupBy) && $this->primaryKey) {
            $builder->groupBy($this->table . '.' . $this->primaryKey);
        }

        // Some databases, like PostgreSQL, need order         // information to consistently return correct results.         if ($builder->QBGroupBy && empty($builder->QBOrderBy) && $this->primaryKey) {
            $builder->orderBy($this->table . '.' . $this->primaryKey, 'asc');
        }

        return $builder->limit(1, 0)->get()->getFirstRow($this->tempReturnType);
    }

    /** * Inserts data into the current table. * This method works only with dbCalls. * * @param array $data Data * * @return bool */

  public function testNodeCompleteMigration() {
    // Confirm there are only complete node migration map tables. This shows     // that only the complete migration ran.     $results = $this->nodeMigrateMapTableCount('7');
    $this->assertSame(0, $results['node']);
    $this->assertSame(8, $results['node_complete']);

    $db = \Drupal::database();
    $this->assertEquals($this->expectedNodeFieldRevisionTable()$db->select('node_field_revision', 'nr')
      ->fields('nr')
      ->orderBy('vid')
      ->orderBy('langcode')
      ->execute()
      ->fetchAll(\PDO::FETCH_ASSOC));
    $this->assertEquals($this->expectedNodeFieldDataTable()$db->select('node_field_data', 'nr')
      ->fields('nr')
      ->orderBy('nid')
      ->orderBy('vid')
      ->orderBy('langcode')
      ->execute()
      ->fetchAll(\PDO::FETCH_ASSOC));

    
$this->assertSession()->responseContains('</body>');

    // Verifying BigPipe assets are present.     $this->assertNotEmpty($this->getDrupalSettings());
    $this->assertContains('big_pipe/big_pipe', explode(',', $this->getDrupalSettings()['ajaxPageState']['libraries']), 'BigPipe asset library is present.');

    // Verify that the two expected exceptions are logged as errors.     $this->assertEquals($log_count + 2, (int) $connection->select('watchdog')->countQuery()->execute()->fetchField(), 'Two new watchdog entries.');
    // Using dynamic select queries with the method range() allows contrib     // database drivers the ability to insert their own limit and offset     // functionality.     $records = $connection->select('watchdog', 'w')->fields('w')->orderBy('wid', 'DESC')->range(0, 2)->execute()->fetchAll();
    $this->assertEquals(RfcLogLevel::ERROR, $records[0]->severity);
    $this->assertStringContainsString('Oh noes!', (string) unserialize($records[0]->variables)['@message']);
    $this->assertEquals(RfcLogLevel::ERROR, $records[1]->severity);
    $this->assertStringContainsString('You are not allowed to say llamas are not cool!', (string) unserialize($records[1]->variables)['@message']);

    // Verify that 4xx responses work fine. (4xx responses are handled by     // subrequests to a route pointing to a controller with the desired output.)     $this->drupalGet(Url::fromUri('base:non-existing-path'));

    // Simulate development.     // Verifying BigPipe provides useful error output when an error occurs
  public function rewind() {
    $this->currentRow = NULL;
    $fields = [];
    foreach ($this->sourceIdFields() as $field) {
      $fields[] = $field;
    }
    foreach ($this->destinationIdFields() as $field) {
      $fields[] = $field;
    }
    $this->result = $this->getDatabase()->select($this->mapTableName(), 'map')
      ->fields('map', $fields)
      ->orderBy('destid1')
      ->execute();
    $this->next();
  }

  /** * Implementation of \Iterator::current(). * * This is called when entering a loop iteration, returning the current row. */
  #[\ReturnTypeWillChange]   public function current() {
    

  protected function buildTestTable($element$limit) {
    $header = [
      ['data' => 'wid'],
      ['data' => 'type'],
      ['data' => 'timestamp'],
    ];
    $query = Database::getConnection()->select('watchdog', 'd')->extend(PagerSelectExtender::class)->element($element);
    $result = $query
      ->fields('d', ['wid', 'type', 'timestamp'])
      ->limit($limit)
      ->orderBy('d.wid')
      ->execute();
    $rows = [];
    foreach ($result as $row) {
      $rows[] = ['data' => (array) $row];
    }
    return [
      '#theme' => 'table',
      '#header' => $header,
      '#rows' => $rows,
      '#empty' => $this->t("There are no watchdog records found in the db"),
    ];
  }

class NewTopicsBlock extends ForumBlockBase {

  /** * {@inheritdoc} */
  protected function buildForumQuery() {
    return Database::getConnection()->select('forum_index', 'f')
      ->fields('f')
      ->addTag('node_access')
      ->addMetaData('base_table', 'forum_index')
      ->orderBy('f.created', 'DESC')
      ->range(0, $this->configuration['block_count']);
  }

}


  /** * {@inheritdoc} */
  public function listAll($prefix = '') {
    try {
      $query = $this->connection->select($this->table);
      $query->fields($this->table, ['name']);
      $query->condition('collection', $this->collection, '=');
      $query->condition('name', $prefix . '%', 'LIKE');
      $query->orderBy('collection')->orderBy('name');
      return $query->execute()->fetchCol();
    }
    catch (\Exception $e) {
      return [];
    }
  }

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