切片收集多次

时间:2019-06-29 09:37:45

标签: php laravel

我有一个包含大量数据的集合。

我正在尝试执行以下操作

  • 获取前18个结果并将其吐出
  • 使用循环获取特定的前3个结果并将其吐出

这是我要执行的操作的示例代码:

$data = DataChampion::query()
    ->selectRaw('
        static_champions.name as champion_name, static_champions.slug as champion_slug, static_champions.image as champion_image,
        static_lanes.slug as lane_slug, static_tiers.slug as tier_slug, static_patches.slug as patch_slug,
        ((sum(data_champions.wins) / sum(data_champions.matches)) * 100) as win_rate
    ')
    ->leftJoin('static_champions', 'static_champions.id', 'data_champions.static_champion_id')
    ->leftJoin('static_lanes', 'static_lanes.id', 'data_champions.static_lane_id')
    ->leftJoin('static_tiers', 'static_tiers.id', 'data_champions.static_tier_id')
    ->leftJoin('static_patches', 'static_patches.id', 'data_champions.static_patch_id')
    ->where('data_champions.static_patch_id', StaticPatch::orderByDesc('id')->first()->id)
    ->groupBy('data_champions.static_champion_id')
    ->orderByDesc('win_rate')
    ->get();

foreach ($data->splice(0, 18) as $data) {
    echo $data->champion_name . '<br>';
}

foreach (['top', 'middle', 'bottom'] as $lane_slug) {
    foreach ($data->where('lane_slug', $lane_slug)->splice(0, 3) as $data) {
        echo $lane_slug . ' - ' . $data->champion_name . '<br>';
    }
}

我不断收到错误消息:

  

调用未定义的方法Illuminate \ Database \ Eloquent \ Builder :: splice()

当我删除foreach (['top', 'middle'...整个循环时,它似乎适用于前18个结果。

如何从单个集合中获取所需的数据,这样我就不必对相同的数据使用多个查询?

2 个答案:

答案 0 :(得分:0)

也许是因为您在该foreach中添加了一个位置,该集合成为了查询生成器,请尝试在该位置之后添加-> get()

答案 1 :(得分:0)

更改以下几行-遍历集合(即$ data)时,不能使用相同的变量名。

foreach ($data->splice(0, 18) as $val) {
    echo $val->champion_name . '<br>';
}

foreach (['top', 'middle', 'bottom'] as $lane_slug) {
    foreach ($data->where('lane_slug', $lane_slug)->splice(0, 3) as $val) {
        echo $lane_slug . ' - ' . $val->champion_name . '<br>';
    }
}