Laravel Excel: 导出变体 headers

Laravel Excel: Export variant headers

我在使用 Laravel Excel 时面临以下挑战,我认为这是最好的电子表格。

所以,让我们每一行都是一个 user 并希望为其 hobbies 生成标题,如下所示:

namehobby_1hobby_2hobby_3 吉姆史密斯,篮球,赛艇,国际象棋,编程

问题是,如果爱好数量可能因用户而异,我如何才能生成上述标题 - 也就是说,用户 John Majer 可能只有 hobby_1 => skateboard.

现在我只是按如下方式打印标题:

 public function headings(): array
    {
        return [
            ...
     ];
}

有什么建议吗?

我认为从技术的角度来看,几个 headers 不是一个好的要求,因为这将使以自动化方式进一步处理数据变得困难,但这可能只是我的观点。 但既然你必须这样做,我的解决方案如下。

获取一个用户的最大爱好。示例查询可能如下所示:

public function headings(): array
    {
        $headers = [
            // all headers before hobbies
        ];
        $result = DB::table('hobby_user')->selectRaw('user_id, count(hobby_id) as total')->groupBy('user_id')->orderBy('total', 'desc')->limit(1)->first();
        $totalHobbies = $result['total'];
        // save total hobbies somewhere in class or whereever so you can use it later to build the right amount of columns for each user
        for ($i = 1; $i <= $totalHobbies; $i++) {
            $headers[] = 'hobby_' . $i;
        }
        // now all headers after hobbies
        $headers[] = '';
        return $headers;
}

当您创建用户条目时,请确保您在 class 或其他地方的某处有可用的爱好数量,这样您就不需要执行相同的查询来获取爱好总数每次导出用户条目时。