Statuses sort alphabetically (approved, completed, requested), not in workflow order. And "activity" should weigh comments as two votes each.
A feature has 29 votes and 2 comments. What's its activity rank?
Reveal answer
✓ Answer
29 + (2 × 2) = 33.
Eloquent performanceLesson 20 of 28
Custom order? Turn it into a SQL expression, then index it if needed.
1 min readIntermediateLesson
Statuses sort alphabetically (approved, completed, requested), not in workflow order. And "activity" should weigh comments as two votes each.
Describe your custom order in SQL so the database can sort by it.
$query->orderBy('status', $direction);
// approved, completed, requested (alphabetical)
$query->orderBy(DB::raw("case
when status = 'requested' then 1
when status = 'approved' then 2
when status = 'completed' then 3
end"), $direction);
Statuses sort in workflow order: requested, approved, completed.
The sort is chosen from ?sort=...&direction=...:
->when(request('sort'), function ($query, $sort) {
switch ($sort) {
case 'title': return $query->orderBy('title', request('direction'));
case 'status': return $query->orderByStatus(request('direction'));
case 'activity': return $query->orderByActivity(request('direction'));
}
})
Activity reuses the counts from withCount(['votes', 'comments']):
$query->orderBy(DB::raw('votes_count + (comments_count * 2)'), $direction);
CASE expression with $table->rawIndex("(case ... end)", 'features_status_ranking_index').activity_rank column and update it on each vote or comment.
Sorting by activity: each row shows votes, comments and the computed rank in brackets. For example, 29 votes + 2 comments × 2 = 33.
Custom order? Turn it into a SQL expression, then index it if needed.
A feature has 29 votes and 2 comments. What's its activity rank?
✓ Answer
29 + (2 × 2) = 33.