Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting best seller courses

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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"

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading