Xethron / migrations-generator

Laravel Migrations Generator: Automatically generate your migrations from an existing database schema.
MIT License
3.32k stars 588 forks source link

Foreign keys with multiple fields #125

Open Lambik opened 7 years ago

Lambik commented 7 years ago

Hi,

I'm using your library not to generate migrations, but to analyse table structure in an external database.

It works fine with regular foreign keys (one field points to another table's field), but when I have a table with a combined primary key, it doesn't work anymore:

CREATE TABLE `boink1` (
    `id1` INT(11) NOT NULL,
    `id2` INT(11) NOT NULL,
    `name` VARCHAR(50) NOT NULL,
    PRIMARY KEY (`id1`, `id2`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;

CREATE TABLE `boink2` (
    `id` INT(11) NOT NULL,
    `message` VARCHAR(50) NOT NULL,
    `boink1_id1` INT(11) NOT NULL,
    `boink1_id2` INT(11) NOT NULL,
    PRIMARY KEY (`id`),
    INDEX `FK_boink2_boink1` (`boink1_id1`, `boink1_id2`),
    CONSTRAINT `FK_boink2_boink1` FOREIGN KEY (`boink1_id1`, `boink1_id2`) REFERENCES `boink1` (`id1`, `id2`) ON UPDATE CASCADE ON DELETE NO ACTION
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB;

Then running the code (from artisan tinker):

>>> $ding = new \Xethron\MigrationsGenerator\Generators\SchemaGenerator('extern', false, false);
=> Xethron\MigrationsGenerator\Generators\SchemaGenerator {#412}
>>> $ding->getForeignKeyConstraints('boink2')                                               => [
     [
       "name" => FK_boink2_boink1,
       "field" => "boink1_id1",
       "references" => "id1",
       "on" => "boink1",
       "onUpdate" => "CASCADE",
       "onDelete" => "NO ACTION",
     ],
   ]

I would expect to see both 'id1' and 'id2' in the 'references' field, as well as 'boink1_id1' and 'boink1_id2' in the 'field' field.

I know it's not really a relevant laravel case, but would it be hard to fix/update?

Lambik commented 7 years ago

Well, probably not that hard... In ForeignKeyGenerator.php the code explicity takes element [0]. Perhaps it could be an option to implode(',', $foreignKey->getLocalColumns())? Or just return the entire array as array, and only later when actually making migrations, take [0]? So I can do the thing I want with your code, and you can still do your goal easily?