ForeignIdColumnDefinition.php 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Database\Schema;
  12. use Hyperf\Stringable\Str;
  13. class ForeignIdColumnDefinition extends ColumnDefinition
  14. {
  15. /**
  16. * The schema builder blueprint instance.
  17. *
  18. * @var Blueprint
  19. */
  20. protected $blueprint;
  21. /**
  22. * Create a new foreign ID column definition.
  23. *
  24. * @param array $attributes
  25. */
  26. public function __construct(Blueprint $blueprint, $attributes = [])
  27. {
  28. parent::__construct($attributes);
  29. $this->blueprint = $blueprint;
  30. }
  31. /**
  32. * Create a foreign key constraint on this column referencing the "id" column of the conventionally related table.
  33. *
  34. * @param null|string $table
  35. * @param string $column
  36. * @return ForeignKeyDefinition
  37. */
  38. public function constrained($table = null, $column = 'id')
  39. {
  40. return $this->references($column)->on($table ?? Str::plural(Str::beforeLast($this->name, '_' . $column)));
  41. }
  42. /**
  43. * Specify which column this foreign ID references on another table.
  44. *
  45. * @param string $column
  46. * @return ForeignKeyDefinition
  47. */
  48. public function references($column)
  49. {
  50. return $this->blueprint->foreign($this->name)->references($column);
  51. }
  52. }