laravel - 跳过不在 Laravel 关系表中的行
问题描述
我在跳过行导入 excel / csv Laravel 到 sql 数据库时遇到问题。有两个关系表,分别是品牌表和项目表。我使用 maatwebsite-excel。
Brand Table:
id brand desc
1 AA details AA
2 AB details AB
3 AC details AC
Item Table
id date brand_id buyer
1 09-02-21 3 Andy
2 09-02-21 1 Jhon
3 09-02-21 2 Daniel
这是一个包含标题的导入文件 excel / csv:
(date) (brand) (buyer)
10-02-21 AC Reimon
10-02-21 AC David
10-02-21 AB Michel
10-02-21 ZA Susy
10-02-21 AA Edgar
10-02-21 NK Rhein
只有 Brands Table 中的品牌会保存到数据库中。不存在的品牌将被跳过。我们想要的是这种类型的数据:
(date) (brand) (buyer)
10-02-21 AC Reimon
10-02-21 AC David
10-02-21 AB Michel
10-02-21 AA Edgar
这是我的 ItemImport.php
class ItemImport implements ToCollection, WithCalculatedFormulas, WithChunkReading, ShouldQueue, WithCustomCsvSettings
{
public function collection(Collection $collection)
{
$collection = $collection->toArray();
//dd($collection);
foreach ($collection as $key => $row){
if($key >= 0){
$brand= Brand::where("brand","like","%".$row['1']."%")->first();
$row['1'] = $brand->id;
Item::create([
'date' => $row['0'],
'brand_id' => $row['1'],
'buyer' => $row['3']
]);
}
}
}
}
在代码中,原来没有跳行功能,所以所有的行都输入到数据库中。即使我想摆脱以下数据:
(date) (brand) (buyer)
10-02-21 ZA Susy
10-02-21 NK Rhein
非常感谢愿意解答我困难的各位。:)
解决方案
希望这对你有用,试试吧。
class ItemImport implements ToCollection, WithCalculatedFormulas, WithChunkReading,
ShouldQueue, WithCustomCsvSettings
{
public function collection(Collection $collection)
{
$collection = $collection->toArray();
//dd($collection);
$array_of_names_excluded=['ZA', 'NK'];
foreach ($collection as $key => $row){
if($key >= 0){
$brand= Brand::whereNotIn("brand", $array_of_names_excluded)
->where("brand","like","%".$row['1']."%")->first();
if($brand){
$row['1'] = $brand->id;
Item::create([
'date' => $row['0'],
'brand_id' => $row['1'],
'buyer' => $row['3']
]);
}
}
}
}
}
推荐阅读
- xslt - 如何从根元素中删除肥皂命名空间
- angular - Angular 6 将活动类添加到另一个 ngFor 的 ngFor 元素
- sql-server - 如何将 OLAP Cube 部署到本地 SQL Server?
- python - 在 tsql 和 pyodbc 中参数化 TOP 值
- dart - 如何在 Visual Studio Code 中为 Dart 变量设置语法高亮
- node.js - 使用 loopback-datasource-juggler 获取环回模型
- python - 如何在 shapefile(arcmap)的属性表中将 'ß' 替换为 'ss'?ASCII 错误
- visual-studio - 为什么点击手势识别器在绝对布局中不起作用?
- python - 如何替换嵌套字典中的值
- c++ - 有没有一种方法可以在 CGAL 中计算 Surface_mesh 对象的 pca?