2018-10-06 14:15:54 +02:00
|
|
|
<?php
|
|
|
|
|
2023-02-03 20:41:59 +01:00
|
|
|
declare(strict_types=1);
|
|
|
|
|
2018-10-06 14:15:54 +02:00
|
|
|
namespace Engelsystem\Migrations;
|
|
|
|
|
|
|
|
use Illuminate\Database\Schema\Blueprint;
|
2018-10-17 01:30:10 +02:00
|
|
|
use stdClass;
|
2018-10-06 14:15:54 +02:00
|
|
|
|
|
|
|
trait ChangesReferences
|
|
|
|
{
|
2020-09-03 11:15:16 +02:00
|
|
|
protected function changeReferences(
|
|
|
|
string $fromTable,
|
|
|
|
string $fromColumn,
|
|
|
|
string $targetTable,
|
|
|
|
string $targetColumn,
|
|
|
|
string $type = 'unsignedInteger'
|
2022-12-14 19:15:20 +01:00
|
|
|
): void {
|
2018-10-06 14:15:54 +02:00
|
|
|
$references = $this->getReferencingTables($fromTable, $fromColumn);
|
|
|
|
|
|
|
|
foreach ($references as $reference) {
|
|
|
|
/** @var stdClass $reference */
|
2022-12-14 19:15:20 +01:00
|
|
|
$this->schema->table($reference->table, function (Blueprint $table) use ($reference): void {
|
2018-10-06 14:15:54 +02:00
|
|
|
$table->dropForeign($reference->constraint);
|
|
|
|
});
|
|
|
|
|
2019-11-10 23:26:23 +01:00
|
|
|
$this->schema->table(
|
|
|
|
$reference->table,
|
2022-12-14 19:15:20 +01:00
|
|
|
function (Blueprint $table) use ($reference, $targetTable, $targetColumn, $type): void {
|
2018-10-06 14:15:54 +02:00
|
|
|
$table->{$type}($reference->column)->change();
|
|
|
|
|
|
|
|
$table->foreign($reference->column)
|
|
|
|
->references($targetColumn)->on($targetTable)
|
2019-09-29 14:00:47 +02:00
|
|
|
->onUpdate('cascade')
|
2018-10-06 14:15:54 +02:00
|
|
|
->onDelete('cascade');
|
2019-11-10 23:26:23 +01:00
|
|
|
}
|
|
|
|
);
|
2018-10-06 14:15:54 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-09-03 11:15:16 +02:00
|
|
|
protected function getReferencingTables(string $table, string $column): array
|
2018-10-06 14:15:54 +02:00
|
|
|
{
|
|
|
|
return $this->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 = ?
|
|
|
|
',
|
|
|
|
[
|
|
|
|
$this->schema->getConnection()->getDatabaseName(),
|
|
|
|
$table,
|
|
|
|
$column,
|
|
|
|
]
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|