所以我完全是 Laravel 的菜鸟,我在这里尝试一些东西。我想将一个 CSV 文件导入两个表,我有一个名为 lists 的表,它将获取列表名称和一个 client_id
。
然后我有一个名为 customers 的表格,它将获得姓氏联系电话以及 client_id
和一个 list_id
。
我想要实现的是导入一个 CSV 文件,该文件将获取文件名并将其存储在列表中,然后通过 CSV 文件创建一个数组,并将数据与列表和客户端 ID 一起导入到客户表中。
我已经完成了第一部分,它正确插入到列表表中,我现在如何从位于存储/文档中的 CSV 创建一个数组,然后将其插入到客户表中?
namespace App\Http\Controllers;
use Input;
use DB;
use Illuminate\Http\Request;
use App\Http\Requests\ListsRequest;
use App\Lists;
use App\Clients;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class ListsController extends Controller {
public function index()
{
// $list_items = Lists::all();
$clients = Clients::all();
return view('lists.show', compact('clients'));
}
public function store(Requests\ListsRequest $request)
{
$input = $request->input();
Lists::create($input);
if (Input::hasFile('name'))
{
$file = Input::file('name');
$name = time() . '-' . $file->getClientOriginalName();
$path = storage_path('documents');
$file->move($path, $name);
// All works up to here
// All I need now is to create an array
// from the CSV and insert into the customers database
}
}
}
我选择使用我接受的答案,但我也使用了另一个答案并让它像这样工作。
public function store(Requests\ListsRequest $request)
{
$input = $request->input();
$client_id = $request->input('client_id');
if (Input::hasFile('name'))
{
$file = Input::file('name');
$name = time() . '-' . $file->getClientOriginalName();
$path = storage_path('documents');
Lists::create(['client_id' => $client_id, 'name' => $name]);
$reader = Reader::createFromPath($file->getRealPath());
// Create a customer from each row in the CSV file
$headers = array();
foreach ($reader as $index => $row)
{
if ($index === 0)
{
$headers = $row;
} else
{
$data = array_combine($headers, $row);
Customers::create($data);
}
}
$file->move($path, $name);
return view('clients');
}
}
原文由 Devin Gray 发布,翻译遵循 CC BY-SA 4.0 许可协议
读取 CSV 文件并将其导入 Laravel 的数据库有 3 个步骤。
在开始之前,我创建了一个示例
test.csv
文件并将其放在我的公用文件夹中的文件夹下:第 1 步和第 2 步;我创建了一个名为
csvToArray
的辅助函数,我现在只是把它放在我的控制器中(这个函数的灵感来自这个 链接)它只是读取 CSV 文件并将其转换为数组:步骤3;这是我的最后一步,读取数组并将其插入我们的数据库:
如果你使用
dd($customerArr)
你会得到这个