Fahad Shaikh
Fahad Shaikh

Reputation: 327

Sort model based on count of nested relationship - Laravel 8

I have three tables categories, courses, and users.

courses and users table has intermediate table user_courses.

They have following relationships

Category Model

public function courses()
{
    return $this->hasMany(Course::class, 'category_id', 'id');
}

Course Model

public function category()
{
    return $this->belongsTo(Category::class, 'category_id', 'id');
}

public function users()
{
    return $this->belongsToMany(User::class, 'user_courses', 'course_id', 'user_id');
}

Now I want all categories with courses which has users and these categories should be order by users_count in descending order.

Is there any eloquent way of achieving it?

Upvotes: 0

Views: 232

Answers (1)

Anurat Chapanond
Anurat Chapanond

Reputation: 2987

You should define a hasManyThrough relationship in your Category model.

public function users()
{
    return $this->hasManyThrough(User::class, Course::class);
}

Then you can sort your user count with the following

Category::with('courses.users')
    ->withCount(['users' => function($query) {
        $query->orderBy('users_count', 'desc');
    }])
    ->get();

Upvotes: 3

Related Questions