summaryrefslogtreecommitdiff
path: root/db/migrations/ChangesReferences.php
blob: 84156c7be186631fb8bbcdfa5b3b7d0eb19a40ef (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<?php

namespace Engelsystem\Migrations;

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Schema\Builder as SchemaBuilder;
use stdClass;

trait ChangesReferences
{
    /**
     * @param string $fromTable
     * @param string $fromColumn
     * @param string $targetTable
     * @param string $targetColumn
     * @param string $type
     */
    protected function changeReferences($fromTable, $fromColumn, $targetTable, $targetColumn, $type = 'unsignedInteger')
    {
        $references = $this->getReferencingTables($fromTable, $fromColumn);

        foreach ($references as $reference) {
            /** @var stdClass $reference */
            /** @var SchemaBuilder $schema */
            $schema = $this->schema;

            $schema->table($reference->table, function (Blueprint $table) use ($reference) {
                $table->dropForeign($reference->constraint);
            });

            $schema->table(
                $reference->table,
                function (Blueprint $table) use ($reference, $targetTable, $targetColumn, $type) {
                    $table->{$type}($reference->column)->change();

                    $table->foreign($reference->column)
                        ->references($targetColumn)->on($targetTable)
                        ->onUpdate('cascade')
                        ->onDelete('cascade');
                }
            );
        }
    }

    /**
     * @param string $table
     * @param string $column
     * @return array
     */
    protected function getReferencingTables($table, $column): array
    {
        /** @var SchemaBuilder $schema */
        $schema = $this->schema;

        return $schema->getConnection()
            ->select(
                '
                    SELECT
                            `TABLE_NAME` as "table",
                            `COLUMN_NAME` as "column",
                            `CONSTRAINT_NAME` as "constraint"
                    FROM information_schema.KEY_COLUMN_USAGE
                    WHERE REFERENCED_TABLE_SCHEMA = ?
                    AND REFERENCED_TABLE_NAME = ?
                    AND REFERENCED_COLUMN_NAME = ?
                ',
                [
                    $schema->getConnection()->getDatabaseName(),
                    $table,
                    $column,
                ]
            );
    }
}