Mysql查询到Laravel查询喜欢%%的问题。

问题描述 投票:0回答:1
SELECT tmsid, RIGHT(tmsid,6) AS max_number 
FROM tms_tables 
WHERE tmsid = (SELECT MAX(tmsid) 
               FROM tms_tables 
               WHERE tmsid LIKE '%1001%' )

如何将其转换为Laravel?

enter image description here

如果我这样做, 我得到一个错误的信息

遇到一个非数字值

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%' )'));
mysql laravel search
1个回答
0
投票

由于你把你的语句包装在(')里面, 你不能使用'%100%'. 所以要用(")来包装你的语句. 试试下面的代码

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%' )"));

0
投票

试试看

$tmsid = 1001;

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 :tmid)"),['tmid' => '%'.$tmsid.'%']);

0
投票

你使用了单引号来包围整个查询字符串,同时也包围了查询中的字段。你应该充分使用查询生成器, 让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%');
     });

这将创建一个与你的查询功能相同的查询。

© www.soinside.com 2019 - 2024. All rights reserved.