php - 如何在 laravel 中使用 Maatwebsite 包连接两个表并通过 excel 导入数据?
问题描述
我正在尝试通过在控制器中使用查询来连接两个用户和客户表
控制器中的导出功能
public function export()
{
//$arrays = [$level_one_array, $level_two_array, $level_three_array];
$arrays = Client::select('clients.*','users.*')->join('users', 'users.id', '=', 'clients.user_id')->where('users.type', '=', 'client')->get();
return Excel::download(new ClientsExport($arrays), 'clients.xlsx');
}
用户和客户表通过 id 连接。我将这个过滤后的数据传递给导出函数
ClientsExport 中的代码
class ClientsExport implements FromCollection
{
/**
* @return \Illuminate\Support\Collection
*/
private $collection;
public function __construct($arrays)
{
$output = [];
foreach ($arrays as $array) {
// get headers for current dataset
$output[] = array_keys($array[0]);
// store values for each row
foreach ($array as $row) {
$output[] = array_values($row);
}
// add an empty row before the next dataset
$output[] = [''];
}
$this->collection = collect($output);
}
public function collection()
{
return $this->collection;
}
}
但我收到错误
[2021-11-09 14:42:58] local.ERROR: array_values() expects parameter 1 to be array, object given {"userId":1,"exception":"[object] (ErrorException(code: 0): array_values() expects parameter 1 to be array, object given at /home/myonecity/public_html/crm/app/Exports/ClientsExport.php:23)
[stacktrace]
如何解决这个问题?
解决方案
在导出功能中进行以下更改。将 get() 替换为 toArray()。
public function export()
{
//$arrays = [$level_one_array, $level_two_array, $level_three_array];
$arrays = Client::select('clients.*','users.*')->join('users', 'users.id', '=', 'clients.user_id')->where('users.type', '=', 'client')->toArray();
return Excel::download(new ClientsExport($arrays), 'clients.xlsx');
}
推荐阅读
- flutter - Flutter:当手机靠近脸时关闭屏幕
- android - Nullptr 异常
- laravel - 路线 [经销商] 未定义。在拉拉维尔?
- sql - 如何使用 group by 编写单个查询以获得以下输出
- c# - AWS Quicksight 嵌入式仪表板 .NET Core 2.1
- mysql - 如何获取每个用户的最新记录?
- mysql - 使用别名的 on 子句中的未知列
- c++ - 如何读取从调用 xt::load_csv() 返回的 xtensor 'xexpression' 对象的元素?
- android - Android Studio 显示来自 Laravel API 的图像
- php - WordPress ajax 请求未通过 PHP 获得价值