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

namespace Engelsystem\Migrations;

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

trait Reference
{
    /**
     * @param Blueprint $table
     * @param bool      $setPrimary
     * @return ColumnDefinition
     */
    protected function referencesUser(Blueprint $table, $setPrimary = false)
    {
        return $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)
    {
        $definition = $table->unsignedInteger($fromColumn);

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

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

        return $definition;
    }
}