首页 > 解决方案 > 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%' )'));

标签: mysqllaravelsearch

解决方案


您正在使用单引号将整个查询字符串括起来以及将查询中的字段括起来。您应该充分利用查询构建器,让 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%');
     });

这应该创建一个与您所拥有的功能等效的查询


推荐阅读