简体   繁体   中英

Laravel hasMany sub-query

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);
  }

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

I found a work around. Using Laravel's reverse function I'm able to get the desired results all I need to do is call reverse on the property.

$post->latestComments->reverse()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM