engelsystem/db/migrations/Reference.php

59 lines
1.5 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
{
/**
* @param Blueprint $table
* @param bool $setPrimary
*/
protected function referencesUser(Blueprint $table, bool $setPrimary = false)
{
$this->references($table, 'users', null, $setPrimary);
}
/**
* @param Blueprint $table
* @param string $targetTable
* @param string|null $fromColumn
* @param bool $setPrimary
2020-11-21 20:54:04 +01:00
*
2019-12-03 20:09:22 +01:00
* @return ColumnDefinition
*/
protected function references(
Blueprint $table,
string $targetTable,
?string $fromColumn = null,
bool $setPrimary = false
): ColumnDefinition {
$fromColumn = $fromColumn ?? Str::singular($targetTable) . '_id';
2019-12-03 20:09:22 +01:00
$col = $table->unsignedInteger($fromColumn);
if ($setPrimary) {
$table->primary($fromColumn);
}
2020-11-21 20:54:04 +01:00
$this->addReference($table, $fromColumn, $targetTable);
return $col;
}
/**
* @param Blueprint $table
* @param string $fromColumn
* @param string $targetTable
*/
protected function addReference(Blueprint $table, string $fromColumn, string $targetTable)
{
$table->foreign($fromColumn)
->references('id')->on($targetTable)
2019-09-29 14:00:47 +02:00
->onUpdate('cascade')
->onDelete('cascade');
}
}