Просмотр файла vendor/illuminate/database/Eloquent/Factories/BelongsToRelationship.php

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