use Drupal\ Core\ Database\ Database;
use Drupal\ taxonomy\ Entity\ Term;
/** * Remove duplicate alias. */
function remove_duplicate_alias_update_8001() {
// Retrieves a \Drupal\Core\Database\Connection which is a PDO instance.
$connection = Database::getConnection();
// Load taxonomy.
$vid = ;
$terms = \Drupal::entityTypeManager() - > getStorage('taxonomy_term') - > loadTree($vid);
$aliasManager = \Drupal::service('path.alias_manager');
foreach($terms as $term) {
// Load alias by path.
$term_alias = $aliasManager - > getAliasByPath('/taxonomy/term/'.$term - > tid);
// Load path by alias.
if (is_numeric(end(explode('-', $term_alias)))) {
$term_alias = substr($term_alias, 0, strrpos($term_alias, "-"));
}
$query = $connection - > select('path_alias', 'a') - > fields('a', ['path']) - > condition('a.alias', '%'.$term_alias.
'%', 'LIKE');
$data = $query - > execute();
$results = $data - > fetchAll();
if (count($results) > 1) {
foreach($results as $key => $value) {
$term_path = explode('/', $value - > path);
if (is_numeric(end($term_path))) {
$term_data = Term::load(end($term_path));
if (count($term_data) == 0 && !empty($term_alias)) {
// Delete duplicate alias.
$connection - > delete('path_alias') - > condition('alias', '%'.$term_alias.
'%', 'LIKE') - > execute();
}
}
}
}
// Save term so that alias will be genreated.
$taxonomy_term = Term::load($term - > tid);
$taxonomy_term - > Save();
}
}