createJunctionMigration.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. /**
  3. * This view is used by console/controllers/MigrateController.php.
  4. *
  5. * The following variables are available in this view:
  6. * @since 2.0.7
  7. * @deprecated since 2.0.8
  8. */
  9. /* @var $className string the new migration class name without namespace */
  10. /* @var $namespace string the new migration class namespace */
  11. /* @var $table string the name table */
  12. /* @var $field_first string the name field first */
  13. /* @var $field_second string the name field second */
  14. echo "<?php\n";
  15. if (!empty($namespace)) {
  16. echo "\nnamespace {$namespace};\n";
  17. }
  18. ?>
  19. use yii\db\Migration;
  20. /**
  21. * Handles the creation of table `<?= $table ?>` which is a junction between
  22. * table `<?= $field_first ?>` and table `<?= $field_second ?>`.
  23. */
  24. class <?= $className ?> extends Migration
  25. {
  26. /**
  27. * {@inheritdoc}
  28. */
  29. public function safeUp()
  30. {
  31. $this->createTable('<?= $table ?>', [
  32. '<?= $field_first ?>_id' => $this->integer(),
  33. '<?= $field_second ?>_id' => $this->integer(),
  34. 'PRIMARY KEY(<?= $field_first ?>_id, <?= $field_second ?>_id)',
  35. ]);
  36. $this->createIndex(
  37. 'idx-<?= $table . '-' . $field_first ?>_id',
  38. '<?= $table ?>',
  39. '<?= $field_first ?>_id'
  40. );
  41. $this->createIndex(
  42. 'idx-<?= $table . '-' . $field_second ?>_id',
  43. '<?= $table ?>',
  44. '<?= $field_second ?>_id'
  45. );
  46. $this->addForeignKey(
  47. 'fk-<?= $table . '-' . $field_first ?>_id',
  48. '<?= $table ?>',
  49. '<?= $field_first ?>_id',
  50. '<?= $field_first ?>',
  51. 'id',
  52. 'CASCADE'
  53. );
  54. $this->addForeignKey(
  55. 'fk-<?= $table . '-' . $field_second ?>_id',
  56. '<?= $table ?>',
  57. '<?= $field_second ?>_id',
  58. '<?= $field_second ?>',
  59. 'id',
  60. 'CASCADE'
  61. );
  62. }
  63. /**
  64. * {@inheritdoc}
  65. */
  66. public function safeDown()
  67. {
  68. $this->dropTable('<?= $table ?>');
  69. }
  70. }