Uploaded image for project: 'PHP ORMs'
  1. PHP ORMs
  2. PHPORM-84

Implement Laravel latestOfMany / oldestOfMany

    • Type: Icon: Improvement Improvement
    • Resolution: Unresolved
    • Priority: Icon: Unknown 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.

       

            Assignee:
            Unassigned Unassigned
            Reporter:
            jerome.tamarelle@mongodb.com Jérôme Tamarelle
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              None
              None
              None
              None