Laravel Maatwebsite 3.1用DB+join导出Excel为空如何处理
Laravel-Excel 3.1 联表查询导出修复方案
你当前导出为空是两个错误导致的:一是违反了FromQuery的接口约定,手动调用了get()方法;二是DB::raw的传参语法错误。以下是修复后的完整代码:
public function query() { return DB::table('complaints') ->join('customers', 'customers.id', '=', 'complaints.customer_id') ->join('technicians', 'technicians.id', '=', 'complaints.technician_id') ->select( 'complaints.*', 'customers.first_name', 'customers.last_name', 'customers.number', 'customers.email_address', 'customers.occupancy_name', 'customers.building_number', 'customers.house_number', 'customers.taluka', 'customers.city', 'customers.address', 'customers.package', 'customers.package_date', 'customers.package_status', 'customers.package_period', 'technicians.first_name as t_fname', 'technicians.last_name as t_lname', 'technicians.number as t_number' ) ->where(function ($query) { $query->where('customers.package', '=', "Platinum") ->whereRaw('timediff(now(), complaints.date ) > ?', ['06:00:00']) ->where('complaints.status', '=', "Assigned"); }) ->orWhere(function ($query) { $query->where('customers.package', '=', "Gold") ->whereRaw('timediff(now(), complaints.date ) > ?', ['24:00:00']) ->where('complaints.status', '=', "Assigned"); }) ->orWhere(function ($query) { $query->where('customers.package', '=', "Silver") ->whereRaw('timediff(now(), complaints.date ) > ?', ['48:00:00']) ->where('complaints.status', '=', "Assigned"); }); }
关键修改说明
- 移除末尾
->get()调用:FromQuery约定要求query方法必须返回未执行的查询构造器,Laravel Excel会自行控制查询执行、分块处理逻辑,手动调用get会直接返回集合,无法被扩展正常识别 - 修正字段选择语法:普通字段选择不需要套
DB::raw,直接传字段名即可,只有需要写原生SQL片段时才需要用到DB::raw或者whereRaw等方法 - 替换原生条件写法:用
whereRaw方法替代原有的where(DB::raw())写法,参数绑定的方式也更安全,避免SQL注入风险 - 直接返回查询构造器:不需要将查询结果赋值给类属性,直接返回构造器即可,Laravel Excel会自动读取返回值执行后续导出逻辑
内容的提问来源于stack exchange,提问作者Ruturaj Vaidya
相关产品推荐
相关产品推荐

