【发布时间】:2016-02-05 09:03:25
【问题描述】:
所以我是 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');
}
}
【问题讨论】:
-
先看看这个stackoverflow.com/questions/21063008/…你不能像你那样直接插入数据库,如果链接没有提供帮助,请告诉我
-
我现在正在尝试 :) 谢谢,稍后会告诉你进展如何
-
好的,所以我尝试了上面编辑过的问题中看到的内容,但现在即使我只是在我拥有的地方返回“你好”,我也会得到空白屏幕
-
您能帮忙解释一下我添加的区域的逻辑吗?
-
一步一步解决问题很重要,所以如果它没有返回你好,这意味着它没有得到文件或者你的if语句返回false,试着写dd( $input) 在 if 语句之前查看您的控制器是否有生命并找出 $input 是否包含您期望的内容