You need to enable JavaScript to run this app. Laravel基于JSON多值extra_category字段关联查询分类名报错
优惠活动
大模型
产品
解决方案
定价
更多

Laravel基于JSON多值extra_category字段关联查询分类名报错

错误根源

你已经为extra_category配置了array类型转换,因此当字段存储多值JSON(如["12","15","23"])时,$post->extra_category返回的是PHP数组,而非单个标量值。
原查询使用where('id', '=', $post->extra_category)的等于比较逻辑不支持传入数组参数,触发了PDO绑定变量数量不匹配的报错。当字段存储单个值时,$post->extra_category是单值(如"15"),等于比较逻辑可正常运行,因此无异常。

修正步骤

控制器层调整查询逻辑

将等于比较的where替换为匹配多值的whereIn,同时增加空值判断避免边缘场景报错:

// 额外分类为空时返回空集合,避免视图遍历报错
$excatname = collect();
// 仅当有额外分类ID时执行查询
if (!empty($post->extra_category)) {
    $excatname = DB::table('categories')
        ->whereIn('id', $post->extra_category)
        ->get();
}
view()->share('excatname', $excatname);

注意:extra_category存储的是字符串格式的数字(如"12")也不影响匹配,MySQL会自动完成类型转换。

(可选)保持分类顺序与存储顺序一致

默认whereIn返回的结果按分类ID升序排列,若需要和extra_category存储的ID顺序一致,可追加orderByRaw排序:

if (!empty($post->extra_category)) {
    $excatname = DB::table('categories')
        ->whereIn('id', $post->extra_category)
        ->orderByRaw('FIELD(id, ' . implode(',', array_map('intval', $post->extra_category)) . ')')
        ->get();
}

视图层无需大改

原有遍历代码可正常运行,因为我们在控制器层已处理了空集合的场景,不会触发遍历错误:

@foreach($excatname as $excatnamez)
    {{ $excatnamez->name }}
@endforeach

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.09 15:54:03