BelongsToRelationship.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. namespace Illuminate\Database\Eloquent\Factories;
  3. use Illuminate\Database\Eloquent\Model;
  4. use Illuminate\Database\Eloquent\Relations\MorphTo;
  5. class BelongsToRelationship
  6. {
  7. /**
  8. * The related factory instance.
  9. *
  10. * @var \Illuminate\Database\Eloquent\Factories\Factory|\Illuminate\Database\Eloquent\Model
  11. */
  12. protected $factory;
  13. /**
  14. * The relationship name.
  15. *
  16. * @var string
  17. */
  18. protected $relationship;
  19. /**
  20. * The cached, resolved parent instance ID.
  21. *
  22. * @var mixed
  23. */
  24. protected $resolved;
  25. /**
  26. * Create a new "belongs to" relationship definition.
  27. *
  28. * @param \Illuminate\Database\Eloquent\Factories\Factory|\Illuminate\Database\Eloquent\Model $factory
  29. * @param string $relationship
  30. * @return void
  31. */
  32. public function __construct($factory, $relationship)
  33. {
  34. $this->factory = $factory;
  35. $this->relationship = $relationship;
  36. }
  37. /**
  38. * Get the parent model attributes and resolvers for the given child model.
  39. *
  40. * @param \Illuminate\Database\Eloquent\Model $model
  41. * @return array
  42. */
  43. public function attributesFor(Model $model)
  44. {
  45. $relationship = $model->{$this->relationship}();
  46. return $relationship instanceof MorphTo ? [
  47. $relationship->getMorphType() => $this->factory instanceof Factory ? $this->factory->newModel()->getMorphClass() : $this->factory->getMorphClass(),
  48. $relationship->getForeignKeyName() => $this->resolver($relationship->getOwnerKeyName()),
  49. ] : [
  50. $relationship->getForeignKeyName() => $this->resolver($relationship->getOwnerKeyName()),
  51. ];
  52. }
  53. /**
  54. * Get the deferred resolver for this relationship's parent ID.
  55. *
  56. * @param string|null $key
  57. * @return \Closure
  58. */
  59. protected function resolver($key)
  60. {
  61. return function () use ($key) {
  62. if (! $this->resolved) {
  63. $instance = $this->factory instanceof Factory
  64. ? ($this->factory->getRandomRecycledModel($this->factory->modelName()) ?? $this->factory->create())
  65. : $this->factory;
  66. return $this->resolved = $key ? $instance->{$key} : $instance->getKey();
  67. }
  68. return $this->resolved;
  69. };
  70. }
  71. /**
  72. * Specify the model instances to always use when creating relationships.
  73. *
  74. * @param \Illuminate\Support\Collection $recycle
  75. * @return $this
  76. */
  77. public function recycle($recycle)
  78. {
  79. if ($this->factory instanceof Factory) {
  80. $this->factory = $this->factory->recycle($recycle);
  81. }
  82. return $this;
  83. }
  84. }