将 CSV 文件导入 Laravel 控制器并将数据插入两个表

新手上路,请多包涵

所以我完全是 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 许可协议

阅读 615
2 个回答

读取 CSV 文件并将其导入 Laravel 的数据库有 3 个步骤。

  1. 读取 CSV 文件
  2. 将其转换为数组
  3. 最后在我们的数据库中创建记录。

在开始之前,我创建了一个示例 test.csv 文件并将其放在我的公用文件夹中的文件夹下:

 name,email,password
user1,email1@email.com,pasxxxxxxxxxword
user2,email2@email.com,pasxxxxxxxxxword
user3,email3@email.com,pasxxxxxxxxxword

第 1 步和第 2 步;我创建了一个名为 csvToArray 的辅助函数,我现在只是把它放在我的控制器中(这个函数的灵感来自这个 链接)它只是读取 CSV 文件并将其转换为数组:

 function csvToArray($filename = '', $delimiter = ',')
{
    if (!file_exists($filename) || !is_readable($filename))
        return false;

    $header = null;
    $data = array();
    if (($handle = fopen($filename, 'r')) !== false)
    {
        while (($row = fgetcsv($handle, 1000, $delimiter)) !== false)
        {
            if (!$header)
                $header = $row;
            else
                $data[] = array_combine($header, $row);
        }
        fclose($handle);
    }

    return $data;
}

步骤3;这是我的最后一步,读取数组并将其插入我们的数据库:

 public function importCsv()
{
    $file = public_path('file/test.csv');

    $customerArr = $this->csvToArray($file);

    for ($i = 0; $i < count($customerArr); $i ++)
    {
        User::firstOrCreate($customerArr[$i]);
    }

    return 'Jobi done or what ever';
}

注意: 此解决方案假设您在 Laravel 项目中有一个模型,并且在您的数据库中有正确的表。

如果你使用 dd($customerArr) 你会得到这个

在此处输入图像描述

原文由 Maytham Fahmi 发布,翻译遵循 CC BY-SA 3.0 许可协议

在您的 store() 方法中,在 lists 表中创建记录,然后遍历CSV文件的内容并将数据插入 customers 表中。为此,您应该在客户和列表之间创建 关系。您最好使用 PHP League 的 CSV 包之 类的东西来读取此类文件:

 public function store(AddCustomersRequest $request)
{
    // Get uploaded CSV file
    $file = $request->file('csv');

    // Create list name
    $name = time().'-'.$file->getClientOriginalName();

    // Create a list record in the database
    $list = List::create(['name' => $name]);

    // Create a CSV reader instance
    $reader = Reader::createFromFileObject($file->openFile());

    // Create a customer from each row in the CSV file
    foreach ($reader as $index => $row) {
        $list->customers()->create($row);
    }

    // Redirect back to where you need with a success message
}

原文由 Martin Bean 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题