Insolita / yii2-migrik

Yii2 Gii-tools for create migration files
106 stars 29 forks source link

From table migration ignores foreign key on delete Cascade #15

Closed dhiraj closed 7 years ago

dhiraj commented 8 years ago

The migration needs to add 'Cascade' in the relation generation.

Insolita commented 8 years ago

what kind of migrations? more info and examples please

dhiraj commented 8 years ago

Sure, I'm creating a "migration file for the specified database table", the first option. My idea is that I will manually create full table schema using GUI like MySQL workbench and then use migrik to generate a migration and switch over to using that.

So I made a user table and an uploads table. The uploads table has a column id_user that is a foreign key to user table's id primary key. I set the foriegn key to cascade delete and update.

When I run the migration, the table gets created as "RESTRICT", because no cascade is supplied in the migration for update and delete. I manually change the generated migration and add cascade in the statement, and then it works.

BEFORE

        $this->addForeignKey('fk_image_id','{{%image}}','id','user', 'id');

AFTER

        $this->addForeignKey('fk_image_id','{{%image}}','id','user', 'id','CASCADE','CASCADE');
Insolita commented 8 years ago

https://github.com/Insolita/yii2-migrik#use-own-templates this can be the decision Copy folder vendor/insolita/yii2-migrik/gii/default_structure into any place of your project (for ex. /common/gii/migrik_templates); modify file relation.php

$this->addForeignKey('fk_<?=$table['tableName']?>_<?=$rel['pk']?>','<?=$table['tableAlias']?>','<?=$rel['pk']?>','<?=$rel['ftable']?>','<?=$rel['fk']?>', 'CASCADE', 'CASCADE');

and register path to you new template folder in config

$config['modules']['gii'] = [
        'class' => 'yii\gii\Module',
        'allowedIPs' => ['127.0.0.1', 'localhost', '::1'],
        'generators' => [
            'migrik'=>[
                        'class'=>\insolita\migrik\gii\StructureGenerator::class,
                        'templates'=>
                        [
                             'custom'=>'@common/gii/migrik_templates/mycustom'
                        ]
            ],
        ]
]

and you be able to choose new template for generate relations with 'cascade' options without manual editiing.

There are different cases and not only 'cascade' options may be used for foreign keys