<?php

use yii\db\Migration;

/**
 * Handles the creation of table `page_page_category`.
 * Has foreign keys to the tables:
 *
 * - `page`
 * - `page_category`
 */
class m171123_141322_create_junction_table_for_page_and_page_category_tables extends Migration
{
    /**
     * @inheritdoc
     */
    public function up()
    {
        $this->createTable('page_to_category', [
            'page_id' => $this->integer(),
            'category_id' => $this->integer(),
            'PRIMARY KEY(page_id, category_id)',
        ]);

        // creates index for column `page_id`
        $this->createIndex(
            'idx-page_to_category-page_id',
            'page_to_category',
            'page_id'
        );

        // add foreign key for table `page`
        $this->addForeignKey(
            'fk-page_to_category-page_id',
            'page_to_category',
            'page_id',
            'page',
            'id',
            'CASCADE'
        );

        // creates index for column `category_id`
        $this->createIndex(
            'idx-page_to_category-category_id',
            'page_to_category',
            'category_id'
        );

        // add foreign key for table `page_category`
        $this->addForeignKey(
            'fk-page_to_category-category_id',
            'page_to_category',
            'category_id',
            'page_category',
            'id',
            'CASCADE'
        );
    }

    /**
     * @inheritdoc
     */
    public function down()
    {
        // drops foreign key for table `page`
        $this->dropForeignKey(
            'fk-page_to_category-page_id',
            'page_to_category'
        );

        // drops index for column `page_id`
        $this->dropIndex(
            'idx-page_to_category-page_id',
            'page_to_category'
        );

        // drops foreign key for table `page_category`
        $this->dropForeignKey(
            'fk-page_to_category-category_id',
            'page_to_category'
        );

        // drops index for column `category_id`
        $this->dropIndex(
            'idx-page_to_category-category_id',
            'page_to_category'
        );

        $this->dropTable('page_to_category');
    }
}
