php - 在导入时拆分分组数据
问题描述
我有一个如下的excel电子表格:
这将产生九个具有该属性的模型:
- 团体
- 柱子
- 价值
我试图使用 Laravel Excel 找到解决方案,但我被卡住了。问题是一行变成了三行,我不知道如何实现,因为我无法覆盖这些行。
<?php
namespace App\Imports;
use App\Models\MyModel;
use Maatwebsite\Excel\Concerns\OnEachRow;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Row;
//use Maatwebsite\Excel\Concerns\WithMapping;
class ForecastImport implements ToModel, OnEachRow
{
function headingRow(): int { return 2; }
/**
* @param array $row
*
* @return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
dd($row);
return new MyModel([
'group' => $row[0],
'column' => $row[1],
'value' => $row[2]
]);
}
public function onRow(Row $row)
{
$entries = array_map(function($entry) {
return [
'group' => $entry[0],
'column' => $entry[1],
'value' => $rowentry2]
];
}, array_chunk($row->toArray(), 3));
/*foreach($entries as $entry) {
$this->model($entry);
}*/
// One row became three
return $entries;
}
}
解决方案
看来您走在正确的轨道上。正如相关文档中所提到的,这个OnEachRow
关注点可以让您更好地控制在非标准情况下发生的事情,其中整行不一定是直接的模型表示(与ToModel
关注点相反)。该文档甚至建议不要将两者混合使用。
就您而言,是什么阻止您按照自己的方式填充模型?虽然我不太了解您模型的三场结构,但我建议您简单地像这样:
<?php
namespace App\Imports;
use App\Models\MyModel;
use Maatwebsite\Excel\Concerns\OnEachRow;
use Maatwebsite\Excel\Row;
class ForecastImport implements OnEachRow
{
function headingRow(): int { return 2; }
public function onRow(Row $row)
{
//splitting the 9-column array into chunks of 3
$entries = array_map(function($entry) {
return [
'group' => $entry[0],
'column' => $entry[1],
'value' => $entry[2]
];
}, array_chunk($row->toArray(), 3));
//populate a model with each chunk
foreach($entries as $entry) {
MyModel::create($entry);
}
}
}
但同样,我看不到与您正在解析的列和组的相关性,因为您只会分配值。无论如何,您可以自己修改它 - 重点是使用OnEachRow
,您可以更自由地自己管理模型创建。在这种情况下,我们每行创建 3 个模型记录,所以我想这应该足够了。如果我误解了什么,请纠正我。快乐编码!
推荐阅读
- c++ - 队列 - 服务器横幅行为
- java - JUnit 5:如何断言在 Scala 中引发了异常?
- docusignapi - 重定向到发件人视图 URL 显示错误
- java - 取消选择 JTree
- android - Kotlin 结构化类约 3000 行 JSON(反)序列化 - 可访问性/存储?
- html - 字体真棒图标没有出现在文本框中
- arrays - 如何在数组中找到最大值和前一个最大值
- react-native - Expo.launchCameraAsync 自定义图像视图?
- android - 通过添加工具栏时,CoordinatorLayout 滚动不起作用
- angularjs - 从异步子函数返回 AngularJS 结果