gpt4 book ai didi

php - Laravel:如何使用 whereIn 方法获取自定义排序的 Eloquent 集合

转载 作者:可可西里 更新时间:2023-11-01 06:42:26 25 4
gpt4 key购买 nike

我有一组产品 ID,我需要根据这些 ID 检索模型集合。数组是这样的:

$ids = array(9, 2, 16, 11, 8, 1, 18);

现在,我正在使用以下代码行来获取集合。

$products = Product::whereIn('id', $ids)->get();

但它会根据产品的 ID 对产品进行排序。例如:1、2、8、9、11、16、18。我需要的是与 $ids 数组中相同的顺序,即 9, 2, 16, 11, 8, 1, 18

我应该怎么做才能获得与数组中相同的顺序?

最佳答案

使用 mysql 的 Field() 函数(如果你使用的是 mysql 数据库)和 laravel 的 DB::raw() 之类的东西

$products = Product::whereIn('id', $ids)
->orderBy(DB::raw("FIELD(id,".join(',',$ids).")"))
->get();

Field() returns the index position of a comma-delimited list

关于php - Laravel:如何使用 whereIn 方法获取自定义排序的 Eloquent 集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47270669/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com