Norway


Quite a typical scenario, but not easy to find the answer. You can easily results by some column, but what if you want to order by related column in child table? Most common example is a forum like Laracasts which shows in order by the latest post in that topic. How to do that?

First, this is our relationship in appTopic.php:

public function posts()
{
    return $this->hasMany(AppPost::class);
}

Now, you need to realize that this wouldn’t work:

$topics = Topic::with('posts')->orderBy('posts.created_at')->get();

What we actually need to do – two things, actually:

1. Describe a separate relationship for the latest post in the topic:

public function latestPost()
{
    return $this->hasOne(AppPost::class)->latest();
}

2. And then, in our controller, we can do this “magic”:

$ = Topic::with('latestPost')->get()->sortByDesc('latestPost.created_at');

Let’s test it out – here’s our topics table.

laravel topics eloquent relations: how to order topics by newest posts? - Screen Shot 2017 12 27 at 11 - Eloquent Relations: how to order topics by newest posts?

Now, let’s show all users order by latest post.
If you look at the , user ID 2 should come first with latest post on 27th day, then user ID 3 with post on 26th day, and then user ID 1 with post on 25th.

$users = User::with('latestPost')->get()->sortByDesc('latestPost.created_at');
foreach ($users as $user) {
    echo $user->id . ' - ' . $user->latestPost->title . ' (' . $user->latestPost->created_at . ')<br />';
}

Result:

laravel users eloquent relations: how to order topics by newest posts? - Screen Shot 2017 12 27 at 11 - Eloquent Relations: how to order topics by newest posts?

So, isn’t that sweet? You can read more about sortBy and sortByDesc methods here.

The post Eloquent Relations: how to order topics by newest posts? appeared first on Laravel Daily.



Source link

LEAVE A REPLY

Please enter your comment!
Please enter your name here