laravel的in查询_laravel 模型查询按照whereIn排序的示例

本文介绍了如何在 Laravel 中使用 Eloquent 模型进行 in 查询并按查询顺序排序。示例代码显示了正确的和错误的使用方式,强调了 FIND_IN_SET 函数在排序中的应用,以及避免在 SQL 语句中错误添加符号的重要性。
摘要由CSDN通过智能技术生成

实例如下所示:

$ids = [5,7,3,1,2];

$data = Content::whereIn('id',$ids)

->select('id')

->get();

//查询结果是想按照wherein的顺序排序

//正确写法

$data = Content::whereIn('id',$ids)

->select('id')

// ->orderBy(\DB::raw('FIND_IN_SET(id, "' . implode(",", $ids) . '"' . ")"))

// ->orderBy(DB::raw("FIND_IN_SET(id, '" . implode(',', $ids) . "'" . ')'))

// ->orderByRaw("FIND_IN_SET(id, '" . implode(',', $ids) . "'" . ')')

->orderBy(\DB::raw('FIND_IN_SET(id, "' . implode(",", $ids) . '"' . ")"))

->get();

中午没睡觉一直调试,心塞...

错误写法

//错误写法

$data = Content::whereIn('id',$ids)

->select('id')

->orderByRaw("FIND_IN_SET('id', "' . implode(",", $ids) . '"' . ")")

->get();

//该写法查询顺序是按照id大小正序排序

原因解析

//正确写法的sql语句为

select `id` from `contents`

order by FIND_IN_SET(id, "5,6,7,4,2,1") asc

//错误写法的sql语句为

select `id` from `contents`

order by 'FIND_IN_SET(id, "5,6,7,4,2,1")' asc

//或者

select `id` from `contents`

order by `FIND_IN_SET(id, "5,6,7,4,2,1")` asc

//FIND_IN_SET()方法外面不要添加任何符号

以上这篇laravel 模型查询按照whereIn排序的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值