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