Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/Illuminate/Database/Eloquent/Relations/HasOneOrMany.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Concerns\InteractsWithDictionary;
use InvalidArgumentException;

abstract class HasOneOrMany extends Relation
{
Expand Down Expand Up @@ -175,13 +176,18 @@ protected function getRelationValue(array $dictionary, $key, $type)
* Build model dictionary keyed by the relation's foreign key.
*
* @param \Illuminate\Database\Eloquent\Collection $results
* @throws \InvalidArgumentException
* @return array
*/
protected function buildDictionary(Collection $results)
{
$foreign = $this->getForeignKeyName();

return $results->mapToDictionary(function ($result) use ($foreign) {
if (! isset($result->{$foreign})) {
throw new InvalidArgumentException('Relation needs foreign key "'.$result->qualifyColumn($foreign).'" to be fetched');
}

return [$this->getDictionaryKey($result->{$foreign}) => $result];
})->all();
}
Expand Down
6 changes: 6 additions & 0 deletions src/Illuminate/Database/Eloquent/Relations/Relation.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use Illuminate\Support\Arr;
use Illuminate\Support\Traits\ForwardsCalls;
use Illuminate\Support\Traits\Macroable;
use InvalidArgumentException;

/**
* @mixin \Illuminate\Database\Eloquent\Builder
Expand Down Expand Up @@ -262,11 +263,16 @@ public function getRelationCountHash($incrementJoinCount = true)
*
* @param array $models
* @param string|null $key
* @throws \InvalidArgumentException
* @return array
*/
protected function getKeys(array $models, $key = null)
{
return collect($models)->map(function ($value) use ($key) {
if (! isset($value->{$key})) {
throw new InvalidArgumentException('Relation needs parent key "'.$value->qualifyColumn($key).'" to be fetched');
}

return $key ? $value->getAttribute($key) : $value->getKey();
})->values()->unique(null, true)->sort()->all();
}
Expand Down