Imagine you have a "posts" model that has many "comments" relation like below.
<?php namespace App\Models; class Post extends Model { public function comments() { return $this->hasMany(Comment::class); } }
Define the Relation
To define the comments relation "orderBy" the number of "upvoes", you can write it like below.
<?php namespace App\Models; class Post extends Model { public function commentsByUpvotes() { return $this->hasMany(Comment::class)->orderBy('upvotes'); } }
Access the Relation
Now when you get the "comments" relation from the post instance, the result will be ordered by the "upvotes" in ascending order.
$firstPostComments = Post::find(1)->commentsByUpvotes;
Leave a reply