mysql - Mysql 查询到 Laravel 查询 Like %% 问题
问题描述
SELECT tmsid, RIGHT(tmsid,6) AS max_number
FROM tms_tables
WHERE tmsid = (SELECT MAX(tmsid)
FROM tms_tables
WHERE tmsid LIKE '%1001%' )
如何将其转换为 Laravel?
如果我这样做,我会收到一个错误
遇到非数值
DB::select(DB::raw('SELECT tmsid, RIGHT(tmsid,6)
as max_number FROM tms_tables WHERE
tmsid=(SELECT MAX(tmsid) FROM tms_tables where tmsid LIKE '%1001%' )'));
解决方案
您正在使用单引号将整个查询字符串括起来以及将查询中的字段括起来。您应该充分利用查询构建器,让 laravel 处理诸如准备语句之类的事情:
DB::table('tms_tables')
->select('tmsid', DB::raw('RIGHT(tmsid, 6) as max_number'))
->where('tmsid', function ($query) {
$query->selectRaw('MAX(tmsid')
->from('tms_tables as tms_tables_inner')
->where('tmsid', 'LIKE', '%1001%');
});
这应该创建一个与您所拥有的功能等效的查询
推荐阅读
- c# - 如果对象比值更接近,则返回 true。(Speherasting)在 Unity 中
- asp.net-core - 带有身份服务器 4 的 Asp.net Core
- wikipedia - Wikipedia API - 在给定日期或期间进行编辑或标记
- sql - 如何在 SQL 中显示来自多个表的数据,但前提是一列数据与另一列匹配?
- sql - 如何让我的代码一直运行?
- angular - 路由器的孩子没有加载
- javascript - 使用 Chrome 控制台移动到新 URL 时,有没有办法让变量保持活动状态?
- python - Pyspark:当我打印累加器时,它给出零值
- python - 是否有用于 jupyter notebook 的文档字符串自动完成工具?
- r - 如何防止闪亮的应用程序变灰?