forked from illuminate/database
/
HasOneOrMany.php
100 lines (84 loc) · 2.2 KB
/
HasOneOrMany.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<?php namespace Illuminate\Database\Eloquent\Relations;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
abstract class HasOneOrMany extends Relation {
/**
* The foreign key of the parent model.
*
* @var string
*/
protected $foreignKey;
/**
* Create a new has many relationship instance.
*
* @param Illuminate\Database\Eloquent\Builder $query
* @param Illuminate\Database\Eloquent\Model $parent
* @param string $foreignKey
* @return void
*/
public function __construct(Builder $query, Model $parent, $foreignKey)
{
$this->foreignKey = $foreignKey;
parent::__construct($query, $parent);
}
/**
* Create a new instance of the related model.
*
* @param array $attributes
* @return mixed
*/
public function create(array $attributes)
{
$foreign = array($this->foreignKey => $this->parent->getKey());
$instance = $this->related->newInstance(array_merge($attributes, $foreign));
return $instance->save();
}
/**
* Set the base constraints on the relation query.
*
* @return void
*/
public function addConstraints()
{
$key = $this->parent->getKey();
$this->query->where($this->foreignKey, '=', $key);
}
/**
* Set the constraints for an eager load of the relation.
*
* @param array $models
* @return void
*/
public function addEagerConstraints(array $models)
{
$this->query->whereIn($this->foreignKey, $this->getKeys($models));
}
/**
* Build model dictionary keyed by the relation's foreign key.
*
* @param Illuminate\Database\Eloquent\Collection $reuslts
* @return array
*/
protected function buildDictionary(Collection $results)
{
$dictionary = array();
// First we will create a dictionary of models keyed by the foreign key of the
// relationship as this will allow us to quickly access all of the related
// models without having to do nested looping which will be quite slow.
foreach ($results as $result)
{
$dictionary[$result->{$this->foreignKey}][] = $result;
}
return $dictionary;
}
/**
* Get the foreign key for the relationship.
*
* @return string
*/
public function getForeignKey()
{
return $this->foreignKey;
}
}