Relationship.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace Illuminate\Database\Eloquent\Factories;
  3. use Illuminate\Database\Eloquent\Model;
  4. use Illuminate\Database\Eloquent\Relations\BelongsToMany;
  5. use Illuminate\Database\Eloquent\Relations\HasOneOrMany;
  6. use Illuminate\Database\Eloquent\Relations\MorphOneOrMany;
  7. class Relationship
  8. {
  9. /**
  10. * The related factory instance.
  11. *
  12. * @var \Illuminate\Database\Eloquent\Factories\Factory
  13. */
  14. protected $factory;
  15. /**
  16. * The relationship name.
  17. *
  18. * @var string
  19. */
  20. protected $relationship;
  21. /**
  22. * Create a new child relationship instance.
  23. *
  24. * @param \Illuminate\Database\Eloquent\Factories\Factory $factory
  25. * @param string $relationship
  26. * @return void
  27. */
  28. public function __construct(Factory $factory, $relationship)
  29. {
  30. $this->factory = $factory;
  31. $this->relationship = $relationship;
  32. }
  33. /**
  34. * Create the child relationship for the given parent model.
  35. *
  36. * @param \Illuminate\Database\Eloquent\Model $parent
  37. * @return void
  38. */
  39. public function createFor(Model $parent)
  40. {
  41. $relationship = $parent->{$this->relationship}();
  42. if ($relationship instanceof MorphOneOrMany) {
  43. $this->factory->state([
  44. $relationship->getMorphType() => $relationship->getMorphClass(),
  45. $relationship->getForeignKeyName() => $relationship->getParentKey(),
  46. ])->create([], $parent);
  47. } elseif ($relationship instanceof HasOneOrMany) {
  48. $this->factory->state([
  49. $relationship->getForeignKeyName() => $relationship->getParentKey(),
  50. ])->create([], $parent);
  51. } elseif ($relationship instanceof BelongsToMany) {
  52. $relationship->attach($this->factory->create([], $parent));
  53. }
  54. }
  55. /**
  56. * Specify the model instances to always use when creating relationships.
  57. *
  58. * @param \Illuminate\Support\Collection $recycle
  59. * @return $this
  60. */
  61. public function recycle($recycle)
  62. {
  63. $this->factory = $this->factory->recycle($recycle);
  64. return $this;
  65. }
  66. }