-
Type:
Improvement
-
Resolution: Unresolved
-
Priority:
Unknown
-
None
-
Affects Version/s: None
-
Component/s: Laravel
-
None
-
None
-
None
-
None
-
None
-
None
-
None
-
None
The latestOfMany/oldestOfMany feature allows to get a single model from a list of related models.
https://laravel.com/docs/10.x/eloquent-relationships#has-one-of-many
Currently, using this method doesn't filter on the latest/newest, but return the full list of related documents.
This feature was introduced in Laravel 8 (PR) and improved in Laravel 10 (PR).
Failing test (need to be checked with an SQL database):
class User { // ... books is defined previously public function latestBook() { return $this->books()->one()->latestOfMany(); // Previously // return $this->hasOne(Book::class, 'author_id')->latestOfMany(); } }
public function testLatestOfMany() { $user = User::create(['name' => 'John Doe']); $book1 = Book::create(['title' => 'Title 1', 'author_id' => $user->_id]); $book2 = Book::create(['title' => 'Title 2', 'author_id' => $user->_id]); $book3 = Book::create(['title' => 'Title 3', 'author_id' => $user->_id]); $latestBook = User::find($user->_id)->latestBook()->get(); $this->assertEquals($book3->_id, $latestBook->_id); }
This may require an aggregation for MIN/MAX query.
- duplicates
-
PHPORM-281 laravel-mongodb - Issue #3231: latestOfMany() doesnt work
-
- Closed
-