如何在Laravel中按字段顺序排序 [英] How to order by where in fields in Laravel
问题描述
我在视图表中针对MYSQL中的产品进行了一些计算,因此我列出了这些ID作为产品参考ID.
I did some calculate in a view table for products in MYSQL, so I list these id for product reference id.
$referenceIds = viewTable::orderBy('score', 'DESC')->lists('product_id');
我想从这些参考ID中获得产品.
And I want to get the product from those reference id.
$products = Product::whereIn('id', $rederenceIds);
产品内容正确,但是顺序错误,如何通过引用ID加载产品订单,我知道我可以使用ORDER BY FIELD(id,' . $fields . ')
在MySQL中完成,但是我想找出Laravel的方式,希望不要使用ORDER BY FIELD
命令,因为这似乎浪费了很多数据库效率.
The product content is correct, but the order is wrong, how to load product order by reference id, I know I can do it in MySQL by using ORDER BY FIELD(id,' . $fields . ')
, but I want to find out Laravel way, and hope not use ORDER BY FIELD
command because it seems waste to much database efficiency.
推荐答案
您将不得不注入一些原始sql,但这并不是一场噩梦:
You will have to inject some raw sql, but it's not a nightmare:
$referenceIds = viewTable::orderBy('score', 'DESC')->lists('product_id');
$referenceIdsStr = implode(',', $referenceIds);
$products = Product::whereIn('id', $rederenceIds)->orderByRaw(DB::raw("FIELD(product_id, $referenceIdsStr)"))->get()->all();
这篇关于如何在Laravel中按字段顺序排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!