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

Laravel Backpack 4 LIKE查询无结果 求技术排查

Laravel Backpack 4 LIKE搜索无结果返回问题

使用Laravel Backpack 4时,自定义列表页搜索逻辑后前端无结果返回,但手动在phpMyAdmin中执行对应SQL能得到3条结果。

代码实现

$this->crud->addClause('where', function ($query) use ($cat, $intranet) {
    $search = request('search');

    $query->where('categoria', "news")
        ->where('is_intranet', $intranet);

    if (isset($search) && isset($search['value'])) {
        $searchTerm = $search['value'];
        $query->where(function ($q) use ($searchTerm) {
            $q->where('titolo', 'LIKE', "%{$searchTerm}%")
                ->orWhere('id', 'LIKE', "%{$searchTerm}%");
        });

        // dd($query->toSql(), $query->getBindings());
    }
});

调试信息

dump得到的查询语句及绑定参数:

select * from `contents` where `categoria` = ? and `is_intranet` = ? and (`titolo` LIKE '%ottobre%' or `id` LIKE '%ottobre%')
array:2 [
  0 => "news"
  1 => "0"
]

手动在phpMyAdmin执行的SQL:

select * from `contents` where `categoria` = "news" and `is_intranet` = "0" and (`titolo` LIKE "%ottobre%" or `id` LIKE "%ottobre%") LIMIT 100

问题排查与解决方案

1. 参数绑定问题

从调试信息看,LIKE条件的%ottobre%未被纳入绑定参数,而是直接拼接进SQL,这可能导致字符编码不匹配或转义问题。修改代码,确保搜索词通过参数绑定传递:

if (isset($search) && isset($search['value'])) {
    $searchTerm = "%{$search['value']}%";
    $query->where(function ($q) use ($searchTerm) {
        $q->where('titolo', 'LIKE', $searchTerm)
          ->orWhere('id', 'LIKE', $searchTerm);
    });
}

2. 字符编码不一致

检查Laravel数据库配置(config/database.php)中mysql的charset和collation,确保与数据库表的编码一致(建议统一为utf8mb4):

'mysql' => [
    // ...
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    // ...
],

3. 模型全局作用域干扰

检查对应模型是否存在全局作用域(如软删除、状态过滤),这些会自动附加查询条件,导致结果被过滤。若需包含被过滤的记录,可在查询中添加:

$query->withTrashed(); // 若使用软删除
// 或移除对应全局作用域

4. 搜索参数结构验证

确认Backpack的搜索参数结构是否符合预期:默认情况下,request('search')是字符串而非数组。若前端自定义了搜索参数结构,需确保$search['value']能正确获取到搜索词,可通过dd(request('search'))验证参数实际值。

5. 原生SQL测试

直接执行原生SQL排查是否为查询构建器问题:

$results = DB::select(
    'select * from `contents` where `categoria` = ? and `is_intranet` = ? and (`titolo` LIKE ? or `id` LIKE ?)',
    ['news', '0', '%ottobre%', '%ottobre%']
);
dd($results);

若此代码能返回结果,说明问题出在查询构建器的使用逻辑上;若仍无结果,需排查数据库连接或数据本身的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 02:55:15