ForeignIdColumnDefinition.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. namespace Illuminate\Database\Schema;
  3. use Illuminate\Support\Str;
  4. class ForeignIdColumnDefinition extends ColumnDefinition
  5. {
  6. /**
  7. * The schema builder blueprint instance.
  8. *
  9. * @var \Illuminate\Database\Schema\Blueprint
  10. */
  11. protected $blueprint;
  12. /**
  13. * Create a new foreign ID column definition.
  14. *
  15. * @param \Illuminate\Database\Schema\Blueprint $blueprint
  16. * @param array $attributes
  17. * @return void
  18. */
  19. public function __construct(Blueprint $blueprint, $attributes = [])
  20. {
  21. parent::__construct($attributes);
  22. $this->blueprint = $blueprint;
  23. }
  24. /**
  25. * Create a foreign key constraint on this column referencing the "id" column of the conventionally related table.
  26. *
  27. * @param string|null $table
  28. * @param string|null $column
  29. * @param string|null $indexName
  30. * @return \Illuminate\Database\Schema\ForeignKeyDefinition
  31. */
  32. public function constrained($table = null, $column = 'id', $indexName = null)
  33. {
  34. return $this->references($column, $indexName)->on($table ?? Str::of($this->name)->beforeLast('_'.$column)->plural());
  35. }
  36. /**
  37. * Specify which column this foreign ID references on another table.
  38. *
  39. * @param string $column
  40. * @param string $indexName
  41. * @return \Illuminate\Database\Schema\ForeignKeyDefinition
  42. */
  43. public function references($column, $indexName = null)
  44. {
  45. return $this->blueprint->foreign($this->name, $indexName)->references($column);
  46. }
  47. }