7

Order By Relationship Count

 2 years ago
source link: https://pineco.de/snippets/order-by-relationship-count/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Order By Relationship Count

Often, we need to use database-level ordering before we retrieve our records and fetch them to models. But also, in some cases, we need to perform the order a bit differently, for example counting the related models.

Let’s say we have a Post model and a Comment model. The Comment model has a belongsTo() relationship with the Post, while the Post has a hasMany() relationship with the comment.

Let’s say we need to order the posts based on how many comments they have. Fortunately, Laravel offers a simple, yet very powerful solution for this issue. Let’s see:

Post::orderBy('comments_count')->get();
Note, the Post model does not have the comments_count field at all. This is handled by Laravel behind the scenes.

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK