【发布时间】:2016-11-28 20:27:09
【问题描述】:
我有 2 个模型想要通过 CVS 导入来填充。第一个模型是零售商店列表,第二个模型是零售商店对应的位置。
这是 CSV 导入:
name,email,website,street_number,street_address,city,country,postcode,latitude,longitude
"Example name",info@example.com,10,"random street",amsterdam,netherlands,4000,52.666,4.3333
RetailStores.php 模型将需要这些值:
name,
email,
website
LocationStores.php 模型将需要这些值:
street_number,
street_address,
city,
country,
postcode,
latitude,
longitude
我将从foreach 循环内的CSV 文件中提取数据并将它们附加到一个空数组变量,从这里将使用一些Eloquent 来填充数据库。以下是我的做法:
$file = Input::file('csv_file');
$data = $this->retailer->processCsv($file);
$retailers = [];
$locations = [];
foreach ($data as $value) {
$retailers[] = array(
'user_id' => Auth::user()->id,
'name' => $value['name'],
'email' => $value['email'],
'website' => $value['website'],
'created_at' => Carbon::now(),
'updated_at' => Carbon::now()
);
$locations[] = array(
'retailer_id' => $value['retailer_id'], // ISSUE HERE
'street_number' => $value['street_number'],
'street_address' => $value['street_address'],
'city' => $value['city'],
'state' => $value['state'],
'country' => $value['country'],
'country_code' => $value['country_code'],
'postcode' => $value['postcode'],
'latitude' => $value['latitude'],
'longitude' => $value['longitude'],
'created_at' => Carbon::now(),
'updated_at' => Carbon::now()
);
Retailer::insert($retailers);
Location::insert($locations);
}
如上所述,我有 2 个独立的模型,即 Retailers 和 Locations。我需要在 $locations 数组中引用零售商 ID。现在我有一个选择,就是让用户在 CSV 文件中为每个位置输入相关的零售商商店 ID,但是人们很好......你知道的。
但是考虑到 CSV 文件将为其拥有的每个位置提供一个 “商店名称”,是否没有办法为每个唯一商店引用增量 ID数组中的名称?例如,如果 CSV 表具有以下值:
Fruit,info@fruit.com,www.fruit.com,1,"apple street",etc
Fruit,info@fruit.com,www.fruit.com,120,"pear parkway",etc
Fruit,info@fruit.com,www.fruit.com,350,"orange avenue",etc
Meat,info@meat.com,www.meat.com,33,"Steak street",etc
Meat,info@meat.com,www.meat.com,33,"Chicken Road",etc
当在 foreach 循环中获取这些值时,有没有一种方法可以为每个重复的商店名称提供一个增量 ID,从而将相关商店引用到其位置?
任何建议,不胜感激。
【问题讨论】: