2018-11-10 20:42:48 +01:00
|
|
|
<?php
|
|
|
|
|
2023-02-03 20:41:59 +01:00
|
|
|
declare(strict_types=1);
|
|
|
|
|
2018-11-10 20:42:48 +01:00
|
|
|
namespace Engelsystem\Migrations;
|
|
|
|
|
|
|
|
use Illuminate\Database\Schema\Blueprint;
|
2019-12-03 20:09:22 +01:00
|
|
|
use Illuminate\Database\Schema\ColumnDefinition;
|
2019-11-27 23:43:21 +01:00
|
|
|
use Illuminate\Support\Str;
|
2018-11-10 20:42:48 +01:00
|
|
|
|
|
|
|
trait Reference
|
|
|
|
{
|
2022-11-06 12:41:52 +01:00
|
|
|
protected function referencesUser(Blueprint $table, bool $setPrimary = false): ColumnDefinition
|
2018-11-10 20:42:48 +01:00
|
|
|
{
|
2022-11-06 12:41:52 +01:00
|
|
|
return $this->references($table, 'users', null, null, $setPrimary);
|
2018-11-10 20:42:48 +01:00
|
|
|
}
|
|
|
|
|
2019-11-27 23:43:21 +01:00
|
|
|
protected function references(
|
|
|
|
Blueprint $table,
|
|
|
|
string $targetTable,
|
|
|
|
?string $fromColumn = null,
|
2022-11-06 12:41:52 +01:00
|
|
|
?string $targetColumn = null,
|
|
|
|
bool $setPrimary = false,
|
|
|
|
string $type = 'unsignedInteger'
|
2019-11-27 23:43:21 +01:00
|
|
|
): ColumnDefinition {
|
|
|
|
$fromColumn = $fromColumn ?? Str::singular($targetTable) . '_id';
|
2022-11-06 12:41:52 +01:00
|
|
|
$col = $table->{$type}($fromColumn);
|
2018-11-10 20:42:48 +01:00
|
|
|
|
|
|
|
if ($setPrimary) {
|
|
|
|
$table->primary($fromColumn);
|
|
|
|
}
|
|
|
|
|
2023-12-06 17:35:39 +01:00
|
|
|
$this->addReference($table, $fromColumn, $targetTable, $targetColumn);
|
2020-11-21 20:54:04 +01:00
|
|
|
|
|
|
|
return $col;
|
|
|
|
}
|
|
|
|
|
2022-11-06 12:41:52 +01:00
|
|
|
protected function addReference(
|
|
|
|
Blueprint $table,
|
|
|
|
string $fromColumn,
|
|
|
|
string $targetTable,
|
2022-11-06 13:57:05 +01:00
|
|
|
?string $targetColumn = null,
|
|
|
|
?string $name = null
|
|
|
|
): void {
|
|
|
|
$table->foreign($fromColumn, $name)
|
2022-11-06 12:41:52 +01:00
|
|
|
->references($targetColumn ?: 'id')->on($targetTable)
|
2019-09-29 14:00:47 +02:00
|
|
|
->onUpdate('cascade')
|
2018-11-10 20:42:48 +01:00
|
|
|
->onDelete('cascade');
|
|
|
|
}
|
|
|
|
}
|