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