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

Laravel数据过滤时报Call to a member function where() on array错误

问题原因

  • 你已经将查询结果通过->toArray()转为了普通PHP数组,普通数组没有Laravel查询构建器/集合的where()方法,直接调用会报方法不存在错误。
  • 循环中同时往$data塞入结构完全不同的$transfer和$pertandingan数组,后续筛选时会出现字段不存在的异常。
  • array_search()仅能返回首个匹配项的下标,无法返回所有符合筛选条件的数据集。
  • 原代码里标题变量$tittle拼写错误,正确应为$title。

修复代码

建议用Laravel集合来处理数据,不需要提前转数组,同时调整循环逻辑,再实现多参数筛选:

// 原始查询保留集合格式,不要提前转数组
$matchs = Matchs::where('type', 'sparring')->where('status','Pending')->whereNull('deleted_at')->get();
$data = collect(); // 初始化Laravel集合对象

foreach ($matchs as $key) {
    $lawan = Matchs::find($key->id)->toArray();
    $pertandingan = Sparring::where('match_id', $key->id)->first()->toArray();
    $dua_arah = MatchTwoTeam::where('match_id', $key->id)->first()->toArray();
    $tim = Team::find($dua_arah['home_team'])->toArray();

    // 把所有需要的字段合并到同一个数组里,不要分开push两类不同结构的数组
    $transfer = [
        'name' => $tim['name'],
        'city' => $lawan['city'],
        'field_cost' => $pertandingan['field_cost'],
        'referee_cost' => $pertandingan['referee_cost'],
        'logo_path' => $tim['logo_path'],
        'nama_lapangan' => $lawan['nama_lapangan'],
        'date' => $lawan['date'],
        // 如需保留$pertandingan的其他字段,直接在这里补充即可
    ];
    $data->push($transfer);
}

// 多维度筛选逻辑,参数存在才执行对应筛选
if ($request->has('name')) {
    // 模糊匹配name字段
    $keyword = $request->input('name');
    $data = $data->filter(function ($item) use ($keyword) {
        return str_contains($item['name'], $keyword);
    });
}
if ($request->has('date')) {
    // 精确匹配date字段
    $data = $data->where('date', $request->input('date'));
}
// 其他字段筛选可以按照上面的逻辑继续扩展

// 最终转数组传给视图
$title = "Sparring";
return view('mode.sparring', [
    'title' => $title,
    'data' => $data->toArray(),
]);

额外优化建议

你当前循环内每次迭代都会执行4次数据库查询,数据量较大时性能损耗非常高,建议改用Laravel的关联预加载(with)功能减少SQL查询次数,提升接口响应速度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 20:15:07