Get the App
SLTechnology News&Howtos  ›  Development  › 

How to sort by relation in Laravel Eloquent

Shulou Source: shulou.com Published: 2022-06-01 04:35:28 10月03日 Update

This article will explain in detail how Laravel Eloquent can be sorted through relationships. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

Sort by relation

A more complicated "technique". Do you want to sort forum topics by the latest posts? The latest updated topics in the forum are very common requirements at the front, right?

First, define a separate relationship for the latest posts on the topic:

Public function latestPost () {return $this- > hasOne (\ App\ Post::class)-> latest ();}

Then, in the controller, we can implement this "magic":

$users = Topic::with ('latestPost')-> get ()-> sortByDesc (' latestPost.created_at'); this is the end of the article on "how to sort through relationships in Laravel Eloquent". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Tags: Sorting articles posts more forums good complex practical topics content common tips controllers articles latest updates knowledge topics requirements magic references Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Huawei Docker Shulou Information Microsoft