【问题标题】:How to show a special string for a column when exporting using laravel-excel?使用 laravel-excel 导出时如何显示列的特殊字符串?
【发布时间】:2019-08-06 03:28:13
【问题描述】:

我正在使用 laravel excel 从“用户”表中导出数据。需要运行查询,并且将返回与查询匹配的所有记录。

我的代码是这样的

class UsersExport implements FromQuery
{
    use Exportable;

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

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

它运行良好,并为我提供了正确的数据。

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

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

我想要的输出是这样的,

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

【问题讨论】:

    标签: laravel maatwebsite-excel


    【解决方案1】:

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

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

    第二种方法是实现FromCollection,然后使用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;
                });
        }
    }
    

    【讨论】:

    • 我没有正确理解第二种方式。能详细点吗?
    猜你喜欢
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 2015-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-02
    相关资源
    最近更新 更多