summaryrefslogtreecommitdiff
path: root/db/migrations/Reference.php
blob: 49a1f9ead652667ef7988ce778fbb3efe46ab9a6 (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
<?php

namespace Engelsystem\Migrations;

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Schema\ColumnDefinition;

trait Reference
{
    /**
     * @param Blueprint $table
     * @param bool      $setPrimary
     */
    protected function referencesUser(Blueprint $table, $setPrimary = false)
    {
        $this->references($table, 'users', 'user_id', $setPrimary);
    }

    /**
     * @param Blueprint $table
     * @param string    $targetTable
     * @param string    $fromColumn
     * @param bool      $setPrimary
     * @return ColumnDefinition
     */
    protected function references(Blueprint $table, $targetTable, $fromColumn, $setPrimary = false): ColumnDefinition
    {
        $col = $table->unsignedInteger($fromColumn);

        if ($setPrimary) {
            $table->primary($fromColumn);
        }

        $table->foreign($fromColumn)
            ->references('id')->on($targetTable)
            ->onUpdate('cascade')
            ->onDelete('cascade');

        return $col;
    }
}