Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering Related Models with Laravel/Eloquent

Tags:

php

orm

laravel

Is it possible to use an orderBy for an object's related models? That is, let's say I have a Blog Post model with a hasMany("Comments"); I can fetch a collection with

$posts = BlogPost::all();

And then run through each post, and display the comment's last edited date for each one

foreach($posts as $post)
{
    foreach($post->comments as $comment)
    {
        echo $comment->edited_date,"\n";
    }
}

Is there a way for me to set the order the comments are returned in?

like image 512
Alan Storm Avatar asked Sep 30 '14 21:09

Alan Storm


2 Answers

This is the correct way:

BlogPost::with(['comments' => function ($q) {
  $q->orderBy('whatever');
}])->get();
like image 140
Jarek Tkaczyk Avatar answered Oct 01 '22 06:10

Jarek Tkaczyk


The returned object from the relationship is an Eloquent instance that supports the functions of the query builder, so you can call query builder methods on it.

foreach ($posts as $post) {
    foreach ($post->comments()->orderBy('edited_date')->get() as $comment) {
        echo $comment->edited_date,"\n";
    }
}

Also, keep in mind when you foreach() all posts like this, that Laravel has to run a query to select the comments for the posts in each iteration, so eager loading the comments like you see in Jarek Tkaczyk's answer is recommended.

You can also create an independent function for the ordered comments like you see in this question.

public function comments() {
    return $this->hasMany('Comment')->orderBy('comments.edited_date');
}

And then you can loop them like you did in your original code.

like image 37
totymedli Avatar answered Oct 01 '22 08:10

totymedli