Сохранение связи терминов при переносе узлов


На самом деле я могу переносить узлы в зависимости от их типа, и автор поставляется с импортом узлов, подобным этому в d2d:

$this->addFieldMapping('uid', 'uid');

Но я не знаю, как сделать то же самое, чтобы сохранить термины, привязанные к узлам..Я считаю, что в источнике Drupal6 термины часто назначаются из основной системы, а не через модуль таксономии контента, который представляет способ Drupal7.

Как вы думаете, я могу это сделать на самом деле, или мне нужно изменить источник и принять способ таксономии контента перед переносом узлов или вообще обновлением с Drupal 6 на Drupal 7?

Спасибо

ИЗМЕНИТЬ: мой код класса миграции

class NodesPageInnovationsMigration extends DrupalNode6Migration {
/* ==============================================================================
* -- Pour limiter l'import aux nodes créés aprés la date indiquée --
* 
* ==============================================================================
*/    
//protected function query() {
//    $query = parent::query();
//    $query->condition('created', strtotime('28-03-2013'), '>');
//    return $query;
// }
public function __construct(array $arguments) {
    parent::__construct($arguments);
    //Le nom machine de la migration de nodes associée comme dépendances
     // $this->dependencies[] = 'D2D_RostandNodes_PageInnovations';

    //On défini la source et la cible depuis les infos de base
      $this->source = new MigrateSourceSQL($this->query(),
      $this->sourceFields,NULL, $this->sourceOptions);


// We're replacing the legacy field_published, which was a text field, with a new date field
    $this->addFieldMapping('field_publish_date', 'field_published');

    //Préservation du NID des nodes importés
     $this->addFieldMapping('field_legacy_nid', 'nid')
         ->description('We have a common field to save the D6 nid');

    /* ==============================================================================
     * -- Mappage de la taxonomie --
     * Assigned terms are represented in Drupal 6 by their vid, migrate to the new term
     * reference field, translating the tid from the legacy value.
     * ==============================================================================
     */
     //$this->addFieldMapping('field_NomduChampCible', 'VidSource')
    //La taxonomie via champs custom ou du core (D6)
   // The first param is for the D7 field name.
    // The second param is for the old site's vocab ID.
    $this->addFieldMapping('taxonomy_vocabulary_1', '1')
        // ->sourceMigration('Tags') // This is the machine name of the tags migration.
         // This tells the migration to match on the term ID instead of the default, which is the term name.
         ->arguments(array('source_type' => 'tid'));

    $this->addFieldMapping('taxonomy_vocabulary_2', '2')
        // ->sourceMigration('Tags') // This is the machine name of the tags migration.
         // This tells the migration to match on the term ID instead of the default, which is the term name.
         ->arguments(array('source_type' => 'tid'));



   //$this->addFieldMapping('field_taxo_vdl', 'field_taxo_vdl'); inutile car dans D7 taxo est un champ

    /* ==============================================================================
     * -- Mappage des champs custom CCK --
     * $this->sourceFields['NomChampSource'] = t('DescriptionChampSource');
     * ==============================================================================
     */
//   $this->sourceFields['field_fichier_joint_lycee'] = t('Joindre un fichier');
//   $this->sourceFields['field_lien_page_lycee'] = t('Liens utiles');
//   $this->sourceFields['field_video_lycee'] = t('Ajout galerie Flickr');

   $this->addFieldMapping('field_video_externe', 'field_video_externe');
   $this->addFieldMapping('field_fichier_joint_innovation', 'field_fichier_joint_innovation');
   $this->addFieldMapping('field_fiche_action_innovation', 'field_fiche_action_innovation');
   $this->addFieldMapping('field_date_evenement', 'field_date_evenement');


   //Les champs custom pour les contenus VDL
   $this->addFieldMapping('field_illus_vdl', 'field_illus_vdl');
   $this->addFieldMapping('field_video_vdl', 'field_video_vdl');
   $this->addFieldMapping('field_galerie_image_vdl', 'field_galerie_image_vdl');
   $this->addFieldMapping('field_choix_galerie_vdl', 'field_choix_galerie_vdl');
   $this->addFieldMapping('field_liens_vdl', 'field_liens_vdl');

   //Correspondance des utilisateurs
   $this->addFieldMapping('uid', 'uid');   
   //$this->addFieldMapping('tnid', 'tnid'); traduction du terme



}
/* ==============================================================================
     * -- Manipulation et mise en forme des données des champs mappés --
     * 
     * ==============================================================================
     */
public function prepareRow($row) {
// Always include this snippet, in case our parent class decides to ignore the row
if (parent::prepareRow($row) === FALSE) {
   return FALSE;
}
//ici le code pour formatter les data
}
}
Author: webmaster pf, 2013-06-17

2 answers

Ознакомьтесь со всеми примерами миграции в руководстве по миграции d2d.

Имеется документация по миграции терминов таксономии и миграции узлов.

Поместите их вместе с документацией для миграции.

Кроме того, мигрируют, перенос дополнительных модулей и перенос модулей d2d во всех них есть примеры модулей, которые содержат очень полезный пример кода. В частности, ознакомьтесь с примером модуля в migrate_d2d, у него есть пример этого.

Там много документации, но это потому, что миграция - сложная задача. Чем больше вы читаете и чем лучше понимаете, тем легче это дается и тем лучше результат.

После того, как вы сделали пару миграций, это становится намного проще.

Для узлов и их таксономий сначала переносятся термины, а затем узлы. Модуль переноса будет отслеживать сопоставление старого идентификатора термина с новым идентификатором термина, затем, когда дело дойдет до узлов, он будет использовать это сопоставление для терминов, прикрепленных к узлам.

Вот как вы отображаете поле таксономии:

Когда вы регистрируете свои крючки:

// Each migration being registered takes an array of arguments, some required
// and some optional. Start with the common arguments required by all - the
// source_connection (connection key, set up in settings.php, pointing to
// the Drupal 6 database) and source_version (major version of Drupal).
$common_arguments = array(
  'source_connection' => 'legacy', // This is the name of a connection in your settings.php file.
  'source_version' => 6, // This is the source drupal version.
);

// Other migration registration here, like users & files.

// For vocabulary migrations, source_vocabulary and destination_vocabulary are
// required arguments. Note that in Drupal 6 vocabularies did not have machine
// names, so we use the vocabulary ID to uniquely identify them.
$vocabulary_arguments = array(
  array(
    'description' => t('Migration of Tags terms from Drupal 6'), // Description for this migration
    'machine_name' => 'Tags', // Migration machine name
    'source_vocabulary' => '5',  // Source vocabulary ID
    'destination_vocabulary' => 'tags', // Destination vocab machine name.
  ),
  array(
    'description' => t('Migration of Category terms from Drupal 6'), // Description for this migration
    'machine_name' => 'Category', // Migration machine name
    'source_vocabulary' => '6',  // Source vocabulary ID
    'destination_vocabulary' => 'category', // Destination vocab machine name.
  ),
  // More migrations for other vocabs.
);

// We're using the migrate_d2d class directly for all of the above.
// You can put other common params here.
$common_vocabulary_arguments = $common_arguments + array(
  'class_name' => 'DrupalTerm6Migration',
);
foreach ($vocabulary_arguments as $arguments) {
  $arguments += $common_vocabulary_arguments;
  // Register the migrations.
  Migration::registerMigration($arguments['class_name'], $arguments['machine_name'], $arguments);
}


// Node migrations.
$node_arguments = array(
  array(
    'class_name' => 'PageMigrationClassName', //  The class name for this migration as we are extending a built in one.
    'description' => t('Migration of page nodes from Drupal 6'), // Description for this migration.
    'machine_name' => 'Page', // Machine name of this migration.
    'source_type' => 'page', // The node type in the old site.
    'destination_type' => 'page', // The node type in the new site.
    // Dependencies. This means this won't run until after the Tags & Category migrations have run.
    'dependencies' => array('Tags', 'Category'),
  ),
  // Other nnode migrations here.
);
foreach ($node_arguments as $arguments) {
  $arguments += $common_arguments;
  // Register the migrations.
  Migration::registerMigration($arguments['class_name'], $arguments['machine_name'], $arguments);
}

Теперь в коде миграции узла страницы вы должны сделать:

class PageMigrationClassName extends DrupalNode6Migration{
  public function __construct(array $arguments) {
    parent::__construct($arguments);

    // Note that we map migrated terms by the vocabulary ID.
    // This is for the Tags vocab.
    // The first param is for the D7 field name.
    // The second param is for the old site's vocab ID.
    // This is how it is stored on the row, eg. $row->5
    $this->addFieldMapping('field_tags', '5')
         ->sourceMigration('Tags') // This is the machine name of the tags migration.
         // This tells the migration to match on the term ID instead of the default, which is the term name.
         ->arguments(array('source_type' => 'tid'));

    // And for the category vocab.
    $this->addFieldMapping('field_category', '6')
         ->sourceMigration('Category')
         ->arguments(array('source_type' => 'tid'));
  }
}

Если вы хотите сопоставить данные с данными, которые уже находятся в новой системе и не были перенесены с помощью модуля переноса, вероятно, есть несколько способов сделать это. Один из способов - использовать API миграции методы.

Вы можете реализовать prepareRow() в своем классе миграции узлов и сделать это:

public function prepareRow($row) {
  // Always include this fragment at the beginning of every prepareRow()
  // implementation, so parent classes can ignore rows.
  if (parent::prepareRow($row) === FALSE) {
    return FALSE;
  }

  // The node's terms are in an array under their vocab ID.
  if (!empty($row->{5})) {
    foreach ($row->{5} as &$tid) {
      // Code here to map term IDs from old to new.
      // Set $tid to the corresponding new site tid.
      // You could call a separate mapping function to do this if you have
      // a lot of terms or complex mapping requirements or something.
    }
  }
  return TRUE;
}

В качестве альтернативы вы можете поместить новые tid в другое место в строке $, например:

$row->mapped_tids_tags = array(3, 7, 4, 8, 6);

Тогда для вашего картографа полей у вас есть:

$this->addFieldMapping('field_tags', 'mapped_tids_tags')

Вместо:

$this->addFieldMapping('field_tags', '5')
 4
Author: rooby, 2013-06-18 11:28:24

Достигните этого с помощью этого кода для d2d 2.1 и перенесите 2.6:

 $this->addFieldMapping('taxonomy_vocabulary_1', '1');
    // This tells the migration to match on the term ID instead of the default, which is the term name.
      $this->addFieldMapping('taxonomy_vocabulary_1:source_type')
     ->defaultValue('tid');

Затем термины, уже существующие и созданные во время обновления ядра, сохраняют свое назначение узлов.

 0
Author: webmaster pf, 2013-06-20 07:34:33