engelsystem/db/migrations/Reference.php

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

49 lines
1.3 KiB
PHP
Raw Normal View History

<?php
namespace Engelsystem\Migrations;
use Illuminate\Database\Schema\Blueprint;
2019-12-03 20:09:22 +01:00
use Illuminate\Database\Schema\ColumnDefinition;
use Illuminate\Support\Str;
trait Reference
{
protected function referencesUser(Blueprint $table, bool $setPrimary = false): ColumnDefinition
{
return $this->references($table, 'users', null, null, $setPrimary);
}
protected function references(
Blueprint $table,
string $targetTable,
?string $fromColumn = null,
?string $targetColumn = null,
bool $setPrimary = false,
string $type = 'unsignedInteger'
): ColumnDefinition {
$fromColumn = $fromColumn ?? Str::singular($targetTable) . '_id';
$col = $table->{$type}($fromColumn);
if ($setPrimary) {
$table->primary($fromColumn);
}
$this->addReference($table, $fromColumn, $targetTable, $targetColumn ?: 'id');
2020-11-21 20:54:04 +01:00
return $col;
}
protected function addReference(
Blueprint $table,
string $fromColumn,
string $targetTable,
?string $targetColumn = null,
?string $name = null
): void {
$table->foreign($fromColumn, $name)
->references($targetColumn ?: 'id')->on($targetTable)
2019-09-29 14:00:47 +02:00
->onUpdate('cascade')
->onDelete('cascade');
}
}