You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Laravel Eloquent查询中添加LIKE模糊匹配?

Laravel 5.8实现LIKE模糊匹配报错解决

场景与问题

我正在使用Laravel 5.8开发,现有如下方法,用于检查请求中是否存在cod_title参数,若存在则执行精确匹配查询:

public function getCourseDefinition()
{
    $course_definition = DB::table('getCourseDefinition');
     
    if (request()->has('cod_title') && request('cod_title'))
        $course_definition = $course_definition->whereRaw("cod_title = ?", [request('cod_title')]);
}

现在需要改成模糊匹配,尝试了以下写法:

$course_definition = $course_definition->whereRaw("cod_title = ?", 'LIKE', [request('cod_title')]);

却触发错误:Array to string conversion

问题原因

  1. whereRaw方法参数格式错误:该方法仅接受两个参数,第一个是SQL语句字符串,第二个是绑定的参数数组。你额外传入了'LIKE'参数,导致框架解析参数时出现数组转字符串的异常。
  2. SQL语句逻辑错误:语句里依然使用=而非LIKE,即便参数正确也无法实现模糊匹配。

正确实现方式

方式一:使用whereRaw实现

public function getCourseDefinition()
{
    $course_definition = DB::table('getCourseDefinition');
     
    if (request()->has('cod_title') && request('cod_title')) {
        $title = request('cod_title');
        // 在SQL语句中使用LIKE,参数添加%通配符实现前后模糊匹配
        $course_definition = $course_definition->whereRaw("cod_title LIKE ?", ["%{$title}%"]);
    }
    
    // 注意:原方法遗漏获取结果的步骤,需添加get()返回数据
    return $course_definition->get();
}

方式二:使用Laravel查询构造器原生where方法(更推荐)

Laravel的where方法支持直接指定操作符,写法更简洁易读:

public function getCourseDefinition()
{
    $course_definition = DB::table('getCourseDefinition');
     
    if (request()->has('cod_title') && request('cod_title')) {
        $course_definition = $course_definition->where('cod_title', 'LIKE', "%".request('cod_title')."%");
    }
    
    return $course_definition->get();
}

注:如果只需要前缀或后缀模糊匹配,去掉对应位置的%即可,比如"{$title}%"(前缀匹配)或"%{$title}"(后缀匹配)。

内容的提问来源于stack exchange,提问作者Pouya Vaghefi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 16:40:41