gpt4 book ai didi

php - 导入标题与数据库字段不同的 Excel 文档 - Laravel 5.2

转载 作者:搜寻专家 更新时间:2023-10-31 21:26:10 25 4
gpt4 key购买 nike

尝试导入带有自定义标题(即人类可读)的 Excel 电子表格,并将其与数据库字段匹配以进行 Excel 导入。

示例:列标题为:地区(例如北美)
数据库列标题为:region_code

知道如何使用 maatwebsite/excel 包和 Eloquent 模型来做到这一点吗?

最佳答案

有几种方法可以解决这个问题。默认情况下,maatwerk-excel 包将 header 转换为 slug。

Note: by default these attributes will be converted to a slug. You can change the default inside the config excel::import.heading. Available options are: true|false|slugged|ascii|numeric|hashed|trans|original

True and slugged will be converted to ASCII as well when excel::import.to_ascii is set to true. You can change the default separator as well inside the config.

source

您将能够通过 slug 对行进行寻址,因此 Region 将变为 region。您可以查看是否有适合您的设置。

循环、映射和保存

复杂性取决于您是否有多个工作表,您可以遍历所有内容并将其保存在每个字段的 Eloquent 模型中,方法是将其映射为 Mark Ba​​ker 在对您的问题的评论中提到的那样。我不知道文件是否已上传,或者您是否从本地文件系统中获取文件,所以我为我的示例选择了文件系统选项:

Excel::load(storage_path('app/public/excel-import.xlsx'), function($reader) {

$results = $reader->get();
foreach($results as $result) {
// Your model namespace here
$model = new \App\ImportItem();
$model->region_code = $result->region;
$model->numeric_code = $result->code;
$model->testfield = $result->test_field;
$model->save();
}
});

当您有大量包含大量字段的 Excel 文件时,这并不容易维护,但如果它们很少且不易更改,这可能是一个解决方案.

批量分配

另一个选项是更改 excel 中的所有标题(如果这是一个选项)然后 Mass Assign通过将上面显示的 foreach 的内容替换为您的模型:

$model = App\ImportItem::create($result->toArray()); 

但请注意,默认情况下,所有 Eloquent 模型都受到保护,不受 Mass Assignment 的影响。查看 documentation查看您是否要设置属性 fillableguarded(注意提到的安全隐患)。我注意到有时在要导入的某些文件的 CellCollectionitems 数组中有一个字段 0 => null (显然是一个空列) , 所以你也可以这样调用它

$reader->ignoreEmpty()->get()

不过请记住,它可能会在其他空白字段上产生不需要的结果,因此您也可以用另一种方式剥离它。

现在,如果您不想重命名 Excel 中的所有列,您还可以定义 mutators在您的模型中,但我认为在这种情况下也不合适。一个例子:

class ImportItem extends Model
{
protected $table = 'importitems';
protected $fillable = [
'region_code',
];

/*
* If you have a field region in the Mass Assignment
* and a field region_code in your database.
*/
public function setRegionAttribute($value)
{
$this->attributes['region_code'] = $value;
}
// Same for each attribute! Ugh what a mess!

也许我白写了所有这些,并且在包和/或 Laravel 本身中实现了一种更简单快捷的方法来进行这样的映射,很抱歉在这种情况下浪费了您的时间。

关于php - 导入标题与数据库字段不同的 Excel 文档 - Laravel 5.2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35733839/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com