You are here

public function DbtngExampleRepository::advancedLoad in Examples for Developers 8

Same name and namespace in other branches
  1. 3.x modules/dbtng_example/src/DbtngExampleRepository.php \Drupal\dbtng_example\DbtngExampleRepository::advancedLoad()

Load dbtng_example records joined with user records.

DBTNG also helps processing queries that return several rows, providing the found objects in the same query execution call.

This function queries the database using a JOIN between users table and the example entries, to provide the username that created the entry, and creates a table with the results, processing each row.

SELECT e.pid as pid, e.name as name, e.surname as surname, e.age as age u.name as username FROM {dbtng_example} e JOIN users u ON e.uid = u.uid WHERE e.name = 'John' AND e.age > 18

See also

Drupal\Core\Database\Connection::select()

http://drupal.org/node/310075

File

dbtng_example/src/DbtngExampleRepository.php, line 237

Class

DbtngExampleRepository
Repository for database-related helper methods for our example.

Namespace

Drupal\dbtng_example

Code

public function advancedLoad() {

  // Get a select query for our dbtng_example table. We supply an alias of e
  // (for 'example').
  $select = $this->connection
    ->select('dbtng_example', 'e');

  // Join the users table, so we can get the entry creator's username.
  $select
    ->join('users_field_data', 'u', 'e.uid = u.uid');

  // Select these specific fields for the output.
  $select
    ->addField('e', 'pid');
  $select
    ->addField('u', 'name', 'username');
  $select
    ->addField('e', 'name');
  $select
    ->addField('e', 'surname');
  $select
    ->addField('e', 'age');

  // Filter only persons named "John".
  $select
    ->condition('e.name', 'John');

  // Filter only persons older than 18 years.
  $select
    ->condition('e.age', 18, '>');

  // Make sure we only get items 0-49, for scalability reasons.
  $select
    ->range(0, 50);
  $entries = $select
    ->execute()
    ->fetchAll(\PDO::FETCH_ASSOC);
  return $entries;
}