| 148 |
lars |
1 |
<?php
|
|
|
2 |
|
|
|
3 |
namespace Illuminate\Database\Eloquent\Relations;
|
|
|
4 |
|
|
|
5 |
use Illuminate\Database\Eloquent\Collection;
|
|
|
6 |
use Illuminate\Database\Eloquent\Model;
|
|
|
7 |
use Illuminate\Database\Eloquent\Relations\Concerns\InteractsWithDictionary;
|
|
|
8 |
use Illuminate\Database\Eloquent\Relations\Concerns\SupportsDefaultModels;
|
|
|
9 |
|
|
|
10 |
class HasOneThrough extends HasManyThrough
|
|
|
11 |
{
|
|
|
12 |
use InteractsWithDictionary, SupportsDefaultModels;
|
|
|
13 |
|
|
|
14 |
/**
|
|
|
15 |
* Get the results of the relationship.
|
|
|
16 |
*
|
|
|
17 |
* @return mixed
|
|
|
18 |
*/
|
|
|
19 |
public function getResults()
|
|
|
20 |
{
|
|
|
21 |
return $this->first() ?: $this->getDefaultFor($this->farParent);
|
|
|
22 |
}
|
|
|
23 |
|
|
|
24 |
/**
|
|
|
25 |
* Initialize the relation on a set of models.
|
|
|
26 |
*
|
|
|
27 |
* @param array $models
|
|
|
28 |
* @param string $relation
|
|
|
29 |
* @return array
|
|
|
30 |
*/
|
|
|
31 |
public function initRelation(array $models, $relation)
|
|
|
32 |
{
|
|
|
33 |
foreach ($models as $model) {
|
|
|
34 |
$model->setRelation($relation, $this->getDefaultFor($model));
|
|
|
35 |
}
|
|
|
36 |
|
|
|
37 |
return $models;
|
|
|
38 |
}
|
|
|
39 |
|
|
|
40 |
/**
|
|
|
41 |
* Match the eagerly loaded results to their parents.
|
|
|
42 |
*
|
|
|
43 |
* @param array $models
|
|
|
44 |
* @param \Illuminate\Database\Eloquent\Collection $results
|
|
|
45 |
* @param string $relation
|
|
|
46 |
* @return array
|
|
|
47 |
*/
|
|
|
48 |
public function match(array $models, Collection $results, $relation)
|
|
|
49 |
{
|
|
|
50 |
$dictionary = $this->buildDictionary($results);
|
|
|
51 |
|
|
|
52 |
// Once we have the dictionary we can simply spin through the parent models to
|
|
|
53 |
// link them up with their children using the keyed dictionary to make the
|
|
|
54 |
// matching very convenient and easy work. Then we'll just return them.
|
|
|
55 |
foreach ($models as $model) {
|
|
|
56 |
if (isset($dictionary[$key = $this->getDictionaryKey($model->getAttribute($this->localKey))])) {
|
|
|
57 |
$value = $dictionary[$key];
|
|
|
58 |
$model->setRelation(
|
|
|
59 |
$relation, reset($value)
|
|
|
60 |
);
|
|
|
61 |
}
|
|
|
62 |
}
|
|
|
63 |
|
|
|
64 |
return $models;
|
|
|
65 |
}
|
|
|
66 |
|
|
|
67 |
/**
|
|
|
68 |
* Make a new related instance for the given model.
|
|
|
69 |
*
|
|
|
70 |
* @param \Illuminate\Database\Eloquent\Model $parent
|
|
|
71 |
* @return \Illuminate\Database\Eloquent\Model
|
|
|
72 |
*/
|
|
|
73 |
public function newRelatedInstanceFor(Model $parent)
|
|
|
74 |
{
|
|
|
75 |
return $this->related->newInstance();
|
|
|
76 |
}
|
|
|
77 |
}
|