Skip to content

Commit ee0f81f

Browse files
authored
Add find sole query builder method (#54667)
1 parent 3fa65d9 commit ee0f81f

File tree

3 files changed

+49
-0
lines changed

3 files changed

+49
-0
lines changed

src/Illuminate/Database/Eloquent/Builder.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -477,6 +477,21 @@ public function find($id, $columns = ['*'])
477477
return $this->whereKey($id)->first($columns);
478478
}
479479

480+
/**
481+
* Find a sole model by its primary key.
482+
*
483+
* @param mixed $id
484+
* @param array|string $columns
485+
* @return TModel
486+
*
487+
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException<TModel>
488+
* @throws \Illuminate\Database\MultipleRecordsFoundException
489+
*/
490+
public function findSole($id, $columns = ['*'])
491+
{
492+
return $this->whereKey($id)->sole($columns);
493+
}
494+
480495
/**
481496
* Find multiple models by their primary keys.
482497
*

src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -696,6 +696,23 @@ public function find($id, $columns = ['*'])
696696
)->first($columns);
697697
}
698698

699+
/**
700+
* Find a sole related model by its primary key.
701+
*
702+
* @param mixed $id
703+
* @param array $columns
704+
* @return TRelatedModel
705+
*
706+
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException<TRelatedModel>
707+
* @throws \Illuminate\Database\MultipleRecordsFoundException
708+
*/
709+
public function findSole($id, $columns = ['*'])
710+
{
711+
return $this->where(
712+
$this->getRelated()->getQualifiedKeyName(), '=', $this->parseId($id)
713+
)->sole($columns);
714+
}
715+
699716
/**
700717
* Find multiple related models by their primary keys.
701718
*

src/Illuminate/Database/Eloquent/Relations/HasOneOrManyThrough.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -342,6 +342,23 @@ public function find($id, $columns = ['*'])
342342
)->first($columns);
343343
}
344344

345+
/**
346+
* Find a sole related model by its primary key.
347+
*
348+
* @param mixed $id
349+
* @param array $columns
350+
* @return TRelatedModel
351+
*
352+
* @throws \Illuminate\Database\Eloquent\ModelNotFoundException<TRelatedModel>
353+
* @throws \Illuminate\Database\MultipleRecordsFoundException
354+
*/
355+
public function findSole($id, $columns = ['*'])
356+
{
357+
return $this->where(
358+
$this->getRelated()->getQualifiedKeyName(), '=', $id
359+
)->sole($columns);
360+
}
361+
345362
/**
346363
* Find multiple related models by their primary keys.
347364
*

0 commit comments

Comments
 (0)