如何按 Laravel 字段中的位置排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19560590/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to order by where in fields in Laravel
提问by Chan
I did some calculate in a view table for products in MYSQL, so I list these id for product reference id.
我在MYSQL中的产品视图表中做了一些计算,所以我列出了这些id作为产品参考id。
$referenceIds = viewTable::orderBy('score', 'DESC')->lists('product_id');
And I want to get the product from those reference id.
我想从这些参考 ID 中获取产品。
$products = Product::whereIn('id', $rederenceIds);
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.
产品内容正确,但是顺序不对,如何通过引用id加载产品订单,我知道我可以在MySQL中使用ORDER BY FIELD(id,' . $fields . ')
,但我想找出Laravel的方式,希望不要使用ORDER BY FIELD
命令,因为它看起来很浪费提高数据库效率。
回答by omar j
You will have to inject some raw sql, but it's not a nightmare:
您将不得不注入一些原始 sql,但这不是一场噩梦:
$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();
回答by Surlavi
If the key is primay key (I think in this question it is ...), you can try this:
如果键是主键(我认为在这个问题中它是......),你可以试试这个:
$products = Product::whereIn('id', $rederenceIds)->get();
$products = array_replace(array_flip($rederenceIds), $products->getDictionary());
The result is Array, not Collection.
结果是Array,而不是Collection。
I don't know whether it has an efficiency problem, but order by field has other problems. For example, order by field is not supported by sqlite so it doesn't work in testing with in-memory database.
不知道是不是效率问题,按字段排序还有其他问题。例如,sqlite 不支持按字段排序,因此它不适用于内存数据库的测试。
回答by Glad To Help
Not sure if I understand this entirely, but if you want the products ordered, you should use
不确定我是否完全理解这一点,但是如果您想要订购的产品,您应该使用
$referenceIds = viewTable::lists('product_id');
$ordered_products = Product::whereIn('id', $rederenceIds)->orderBy('id', 'DESC')->get();