May 15, 2019 in Drupal 8
How can you query for nodes, terms etc of a drupal 7 website from your drupal 8 website?
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();
}