0

I want to query users, nodes etc in my D7 database that I am currently migrating to D8 to compare with the migrated content.

I want to use custom Drush commands to run some checks.

Is this possible?

  • No, not really. You can query data from as secondary database, Drupal or otherwise, but you won't be able to load D8 objects from a D7 database - the underlying architecture is incompatible. – Jaypan May 3 at 4:19
  • Ah ok I thought that might be the case. Thanks. Great talk @DrupalSouth too btw ;) – dibs May 3 at 4:22
  • Thanks! (post must be 15 characters) – Jaypan May 3 at 5:08
3

You can add external databases in your settings.php file:

$databases['external']['default']= array(
  'database'=>'',
  'username'=>'',
  'password'=>'',
  'prefix'=>'',
  'host'=>'',
  'port'=>'3306',
  'namespace'=>'Drupal\\Core\\Database\\Driver\\mysql',
  'driver'=>'mysql',
);

Then, in a custom module you can query for nodes, terms etc.

// Switch to external database
\Drupal\Core\Database\Database::setActiveConnection('external');

// Get a connection going
$db = \Drupal\Core\Database\Database::getConnection();

$vid = 5; // The vocabulary I want to query
$query = $db->select('taxonomy_term_data', 't');
$query
  ->join('taxonomy_term_hierarchy', 'h', 'h.tid = t.tid');
$query
  ->addTag('translatable')
  ->addTag('taxonomy_term_access')
  ->fields('t')
  ->fields('h', array(
    'parent',
  ))
  ->condition('t.vid', $vid)
  ->orderBy('t.weight')
  ->orderBy('t.name');
$results = $query->execute()->fetchAll();

Switch back to your current db

\Drupal\Core\Database\Database::setActiveConnection();

Save the results to a d8 vocabulary

foreach($results as $result) {
  Term::create([
    'tid' => $result->tid,
    'name' => $result->name,
    'vid' => 'my_d8_vocabulary_name'
   ])->enforceIsNew()->save();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.