Laravel 8中使用Eloquent为routes查询条件添加引号的方法
Laravel 8 Eloquent 字符串查询条件引号处理及字段自增问题解决
原始代码
Acessos::where('user_id',$uid)->where('routes','=',$routes )->update(['qtd_acessos' => 'qtd_acessos + 1'] );
报错信息
SQLSTATE[HY000]: General error: 1366 Incorrect integer value:
'qtd_acessos + 1' for column 'qtd_acessos' at row 2 (SQL: updateacessossetqtd_acessos= qtd_acessos + 1 whereuser_id= 3 androutes= /home)
1. 为routes查询条件添加引号的正确方式
在Eloquent中,只要通过where('routes', '=', $routes)的方式传入字符串变量作为条件值,Laravel会自动通过参数绑定为字符串添加引号,既保证SQL语法正确,又能避免SQL注入风险。你在报错日志中看到的routes = /home未加引号,是日志显示的预处理SQL简化结果,实际执行时参数绑定会自动补上引号。
如果需要手动指定固定字符串条件(不推荐,易引发SQL注入),可以使用whereRaw包裹带引号的表达式:
Acessos::where('user_id', $uid)->whereRaw("routes = '/home'")
2. 解决qtd_acessos字段自增的错误
你当前的更新写法错误,因为Eloquent会把'qtd_acessos + 1'当作普通字符串值存入整数列,导致类型不匹配报错。有两种正确实现字段自增的方式:
方式一:使用DB::raw执行SQL表达式
Acessos::where('user_id', $uid)->where('routes', $routes) ->update(['qtd_acessos' => DB::raw('qtd_acessos + 1')]);
方式二:使用Laravel内置的increment方法(更简洁)
Acessos::where('user_id', $uid)->where('routes', $routes) ->increment('qtd_acessos');
内容的提问来源于stack exchange,提问作者Cleber Castiglioni
相关产品推荐
相关产品推荐

