Home > front end >  Getting best seller courses
Getting best seller courses

Time:01-09

I'm trying to get best seller courses. but something is going wrong...

$items = DB::table('orders')->select('course_id', DB::raw('COUNT(course_id) as count'))
    ->groupBy('course_id')->orderBy("count", 'desc')->get();

    $courseIds = [];

    foreach($items as $item) {
        array_push($courseIds, $item->course_id);
    }
   
    $bestSellings = Course::whereIn('id', $courseIds)->get();

So when i do dd on $courseIds i'm getting

array:3 [▼
  0 => 4
  1 => 1
  2 => 2
]

and yes it's must be like that because most selling course is number 4 then goes number 1 and then number to but when i try dd on $bestSellings i'm getting 1 course then 2 course then 4 course : / why? what can i do?

CodePudding user response:

If you are using MySQL, then you could use 'ORDER BY FIELD':

$fieldOrder = join(", ", $courseIds);
$bestSellings = Course::whereIn('id', $courseIds)
  ->orderByRaw("FIELD(id, $fieldOrder)")
  ->get();

See: https://www.mysqltutorial.org/mysql-order-by/ "Using MySQL ORDER BY clause to sort data using a custom list"

  •  Tags:  
  • Related