BelongsToManyRelationship.php 2.0 KB

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