Skip to content

Commit

Permalink
make sole relationship friendly (#36200)
Browse files Browse the repository at this point in the history
  • Loading branch information
themsaid authored Feb 9, 2021
1 parent b6e38e8 commit 196aa04
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/Illuminate/Database/Eloquent/Relations/Relation.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Database\MultipleRecordsFoundException;
use Illuminate\Database\Query\Expression;
use Illuminate\Support\Arr;
use Illuminate\Support\Traits\ForwardsCalls;
Expand Down Expand Up @@ -151,6 +153,30 @@ public function getEager()
return $this->get();
}

/**
* Execute the query and get the first result if it's the sole matching record.
*
* @param array|string $columns
* @return \Illuminate\Database\Eloquent\Model
*
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException
* @throws \Illuminate\Database\MultipleRecordsFoundException
*/
public function sole($columns = ['*'])
{
$result = $this->take(2)->get($columns);

if ($result->isEmpty()) {
throw (new ModelNotFoundException)->setModel(get_class($this->model));
}

if ($result->count() > 1) {
throw new MultipleRecordsFoundException;
}

return $result->first();
}

/**
* Execute the query as a "select" statement.
*
Expand Down
14 changes: 14 additions & 0 deletions tests/Database/DatabaseEloquentIntegrationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -805,6 +805,20 @@ public function testHasOnMorphToRelationship()
$this->assertEquals(1, $photos->count());
}

public function testBelongsToManyRelationshipModelsAreProperlyHydratedWithSoleQuery()
{
$user = EloquentTestUserWithCustomFriendPivot::create(['email' => 'taylorotwell@gmail.com']);
$user->friends()->create(['email' => 'abigailotwell@gmail.com']);

$user->friends()->get()->each(function ($friend) {
$this->assertTrue($friend->pivot instanceof EloquentTestFriendPivot);
});

$soleFriend = $user->friends()->where('email', 'abigailotwell@gmail.com')->sole();

$this->assertTrue($soleFriend->pivot instanceof EloquentTestFriendPivot);
}

public function testBelongsToManyRelationshipModelsAreProperlyHydratedOverChunkedRequest()
{
$user = EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);
Expand Down

0 comments on commit 196aa04

Please sign in to comment.