Laravel 查询中 whereIn() 与 where() 的正确使用详解

在 laravel 中,`wherein()` 要求第二个参数必须是数组,而 `request('filename')` 返回的是字符串,直接传入会导致类型错误;应改用 `where()` 进行精确匹配,或对输入做数组转换后再使用 `wherein()`。

你遇到的错误:

Argument 1 passed to Illuminate\Database\Query\Builder::cleanBindings() must be of the type array, string given

根本原因在于这一行代码:

$media = $media->whereIn('med_name', request('fileName'));

whereIn('column', $array) 是为「列值是否存在于指定数组中」设计的,例如查找 med_name 为 'report.pdf' 或 'logo.png' 等多个可能值之一的记录。但 request('fileName')(来自 )返回的是一个字符串(如 "invoice"),而非数组 —— 因此 Laravel 底层校验失败,抛出类型异常。

✅ 正确做法取决于你的业务需求:

✅ 场景一:按文件名完全匹配(最常见)

用户在搜索框输入 invoice,你想查 med_name = 'invoice' 的记录:

if (request()->has('fileName') && trim(request('fileName')) !== '') {
    $media = $media->where('med_name', request('fileName'));
}
? 提示:使用 trim() 替代 != "" 更健壮,避免空格干扰。

✅ 场景二:支持模糊搜索(推荐体验)

用户输入 invo,应匹配 invoice.pdf、invo_2025.xlsx 等:

if (request()->has('fileName') && trim(request('fileName')) !== '') {
    $search = '%' . trim(request('fileName')) . '%';
    $media = $media->where('med_name', 'like', $search);
}

✅ 场景三:按多个文件名筛选(需修改前端)

若真需 whereIn(如多选文件名),则前端 应改为数组形式(如 name="fileName[]"),并确保后端接收为数组:


后端校验并安全使用:

$names = request('fileName', []);
if (is_array($names) && !empty($names)) {
    $media = $media->whereIn('med_name', $names);
}

⚠️ 额外建议:优化你的 select() 方法

当前代码存在两个潜在问题:

  1. N+1 查询风险:foreach ($media as ...) 内部又执行 MediaLibrary::where(...)->get(),每页 15 条就触发 15 次额外查询;
  2. 类型强制转换隐患:return ["files"=>(object) $files, ...] 将数组转为 stdClass,但在 Blade 中访问 $files[0]->path['full'] 易出错,建议保持数组结构或使用集合。

✅ 推荐重构内层查询为关联预加载(若模型已定义关系),或使用 groupBy + with() 一次性获取同组所有尺寸:

// 示例:按 med_group 分组聚合路径(需数据库支持 JSON_AGG 或 GROUP_CONCAT)
$mediaWithPaths = MediaLibrary::selectRaw('*, JSON_OBJECTAGG(med_dimension, med_path) as path_map')
    ->where('med_dimension', 'full')
    ->when(request('fileName'), fn($q) => $q->where('med_name', request('fileName')))
    ->when(request('mediaType'), fn($q) => $q->whereIn('med_extension', (array) request('mediaType')))
    ->groupBy('med_group')
    ->latest()
    ->paginate(15);

但更简单稳妥的方式是:先获取分页后的 full 记录,再用一次查询批量获取所有相关尺寸路径,然后在 PHP 层关联组装 —— 平衡可读性与性能。

✅ 总结

用法 适用场景 参数类型 示例
where('col', $value) 单值精确匹配 string / int where('med_name', 'report.pdf')
where('col', 'like', $pattern) 模糊匹配(推荐搜索) string where('med_name', 'like', '%report%')
whereIn('col', $array) 多值精确匹配 array whereIn('med_name', ['a.pdf','b.jpg'])

立即修复方案(对应你当前表单):
将 select() 方法中的错误行:

$media = $media->whereIn('med_name', request('fileName'));

替换为:

if (request()->has('fileName') && trim(request('fileName')) !== '') {
    $media = $media->where('med_name', 'like', '%' . trim(request('fileName')) . '%');
}

这样既解决报错,又提升用户体验 —— 用户无需输入完整文件名即可检索。