我正在努力獲得暢銷課程。但是出了點問題……
$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();
所以當我在 $courseIds 上做 dd 時,我得到了
array:3 [▼
0 => 4
1 => 1
2 => 2
]
是的,一定是這樣,因為大多數銷售課程是第 4 門然后是第 1 門然后是第 我能做什么?
uj5u.com熱心網友回復:
如果您使用的是 MySQL,那么您可以使用“ORDER BY FIELD”:
$fieldOrder = join(", ", $courseIds);
$bestSellings = Course::whereIn('id', $courseIds)
->orderByRaw("FIELD(id, $fieldOrder)")
->get();
請參閱:https : //www.mysqltutorial.org/mysql-order-by/ “使用 MySQL ORDER BY 子句使用自定義串列對資料進行排序”
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/407027.html
標籤:
