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%' )'));
由于你把你的语句包装在(')里面, 你不能使用'%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%' )"));
试试看
$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.'%']);
你使用了单引号来包围整个查询字符串,同时也包围了查询中的字段。你应该充分使用查询生成器, 让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%');
});
这将创建一个与你的查询功能相同的查询。