Home > front end >  Sort By date in hasMany relation first record for Laravel project
Sort By date in hasMany relation first record for Laravel project

Time:12-06

I have a courses table and every course has many sessions,

So I need to sort courses by the first session of the course date for Laravel Project.

CodePudding user response:

this way you can set a method in Course model to get the oldest Session model(which means first session):

public function oldestSession()
{
   return $this->hasOne(Session::class)->oldestOfMany();
}

and then you may simply query your course model by adding constraints on that method :

$courses = Course::with(['oldestSession' => function ($query) {
    $query->orderBy('created_at', 'desc');
}])->get();
  • Related