Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel hasMany sub-query

Tags:

sql

php

laravel

I have a laravel hasMany relationship and I want to fetch the last 10 comments from a table and order them in descending order. This is how my table looks like

id  |   user_id |   comment_text
----------------------------------------------------------
1       30          foo
2       23          bar
3       17          hello
4       30          world
5       12          lorem
6       10          ipsum
7       17          dummy

My results should be

id  |   user_id |   comment_text
----------------------------------------------------------
5       12          lorem
6       10          ipsum
7       17          dummy    

How I'm running the query to get the expected results

SELECT * FROM (
    SELECT * FROM comments ORDER BY id DESC LIMIT 3
) sub
ORDER BY id ASC

How can I do this in a laravel model? Can I run a subquery in a relationship? This is my implementation so far

public function latestComments($limit = 3)
  {
    return $this->hasMany(Comment::class)     
      ->orderByDesc('id')
      ->limit($limit);
  }
like image 778
sammyukavi Avatar asked Sep 18 '25 10:09

sammyukavi


1 Answers

You are on the right path, just correct it a bit:

public function latestComments($limit = 3)
{
     return $this->hasMany(Comment::class)     
        ->orderBy('id', 'desc')
        ->take($limit);
}

You can read more of take and orderBy up on official docs

like image 88
Nikola Gavric Avatar answered Sep 19 '25 23:09

Nikola Gavric