laravel批量插入, Maatwebsite\Excel上传获取数据

laravel批量插入

之前有人说laravel没有批量插入,是不对的,不仅有,而且很简单:
Elequent方法:

$res = User::insert($data);

DB方法:

$res = \DB::table('user)->insert($data);

下面演示一下从excel上传批量插入数据:

	use Maatwebsite\Excel\Facades\Excel;
	use Validator;
	....
	
    /**
     * 读取用户上传的excel文件
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function readExcelOnly(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'file' => 'required|file|max:3072',
        ]);
        if ($validator->fails()) {
            $first_error = $validator->errors()->first();
            return $this->outPutJson('', 201, $first_error);
        }
        $file = $request->file('file');
        //获取文件后缀,必须是xls,xlsx类型,excel类型比较复杂,不能使用laravel的mimes或者mimetypes判断
        $ext = $file->getClientOriginalExtension();
        if (!in_array($ext, ['xlsx', 'xls'])) {
            return $this->outPutJson('', 201, '必须是excel文件!');
        }
        $data = Excel::toArray(new FormDataImport(), $file);
        #如果需要批量插入,请调用下面的方法
        // $this->batchInserFormData($data[0]);
        return $this->outPutJson($data);
    }

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SHUIPING_YANG

你的鼓励是我创作的最大动力。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值