master

laravel/framework

Last updated at: 29/12/2023 09:23

ForeignIdColumnDefinition.php

TLDR

This file defines the ForeignIdColumnDefinition class, which extends the ColumnDefinition class. It contains two methods:

  • constrained: This method creates a foreign key constraint on a column, referencing the "id" column of a conventionally related table.
  • references: This method specifies which column the foreign ID references on another table.

Classes

ForeignIdColumnDefinition

This class is responsible for creating a new foreign ID column definition. It extends the ColumnDefinition class and contains the following methods:

  • __construct: This method initializes a new instance of the class, setting the $blueprint property.
  • constrained: This method creates a foreign key constraint on the column, referencing the "id" column of the conventionally related table.
  • references: This method specifies which column the foreign ID references on another table.
<?php

namespace Illuminate\Database\Schema;

use Illuminate\Support\Str;

class ForeignIdColumnDefinition extends ColumnDefinition
{
    /**
     * The schema builder blueprint instance.
     *
     * @var \Illuminate\Database\Schema\Blueprint
     */
    protected $blueprint;

    /**
     * Create a new foreign ID column definition.
     *
     * @param  \Illuminate\Database\Schema\Blueprint  $blueprint
     * @param  array  $attributes
     * @return void
     */
    public function __construct(Blueprint $blueprint, $attributes = [])
    {
        parent::__construct($attributes);

        $this->blueprint = $blueprint;
    }

    /**
     * Create a foreign key constraint on this column referencing the "id" column of the conventionally related table.
     *
     * @param  string|null  $table
     * @param  string|null  $column
     * @param  string|null  $indexName
     * @return \Illuminate\Database\Schema\ForeignKeyDefinition
     */
    public function constrained($table = null, $column = 'id', $indexName = null)
    {
        return $this->references($column, $indexName)->on($table ?? Str::of($this->name)->beforeLast('_'.$column)->plural());
    }

    /**
     * Specify which column this foreign ID references on another table.
     *
     * @param  string  $column
     * @param  string  $indexName
     * @return \Illuminate\Database\Schema\ForeignKeyDefinition
     */
    public function references($column, $indexName = null)
    {
        return $this->blueprint->foreign($this->name, $indexName)->references($column);
    }
}