使用 laravel-excel 导出时如何显示列的特殊字符串?

How to show a special string for a column when exporting using laravel-excel?

我正在使用 laravel excel 从 'User' table 导出数据。查询需要 运行,并且所有匹配查询的记录都将 return。

我的代码就像

class UsersExport implements FromQuery
{
    use Exportable;

    public function __construct(string $code)
    {
        $this->code = $code;
    }

    public function query()
    {
        return Tantousya::query()->where('code','>=',$this->code); 
    }
}

它工作完美,给我正确的数据。

但是,在用户 table 中有一个 "password" 列。客户希望我显示像“*****”这样的字符串,而不是显示加密后的密码。如果未设置密码则显示“”(空白字符串)。

为了更好地说明,我当前的输出是这样的,

我想要的输出是这样的,

如何更改查询函数以获得所需的输出?

我认为你应该尝试这样的事情:

public function query()
{
    return Tantousya::query()->select(['*', \DB::raw("'***' as password")])->where('code','>=',$this->code); 
}

第二种方法是实现FromCollection then use the map方法来改变值。

像这样:

use Maatwebsite\Excel\Concerns\FromCollection;

class UserExport implements FromCollection {

    public function collection()
    {
        return User::select(['*'])
            ->get()
            ->map(function($item) {
                $collection = $item;
                $collection['password'] = '***';
                return $collection;
            });
    }
}