【问题标题】:Import [insert or update] Excel/CSV to MySQL database using maatwebsite in laravel 7使用 laravel 7 中的 maatwebsite 将 [插入或更新] Excel/CSV 导入 MySQL 数据库
【发布时间】:2022-12-31 19:45:45
【问题描述】:

导入/上传 excel 文件时,如果数据已存在于 excel 文件中,则在数据库中更新它或插入它。这意味着在插入之前应该检查数据库。所以,任何人都请帮助解决这个问题:

这是客户的导入类:

<?php

namespace App\Imports;

use App\Customer;
use Illuminate\Validation\Rule;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithValidation;
use Maatwebsite\Excel\Concerns\Importable;

class ImportCustomers implements ToModel, WithHeadingRow, WithValidation
{
    use Importable;
    /**
    * @param array $row
    *
    * @return \Illuminate\Database\Eloquent\Model|null
    */

    public function model(array $row)
    {

        // Check mobile already exists
       /* $count = Customer::where('mobile',$row['mobile'])->count();
       dd($count);
       if($count > 0){
          return null;
       } */
        return new Customer([
            'customer_name' => $row['customer_name'],
            'mobile' => $row['mobile'],
            'email' => $row['email']
        ]);
    }

    

    public function rules(): array
    {
        return [
             '*.customer_name' => 'required',
             '*.mobile' => 'required|unique:customers',
             '*.email' => 'required',

        ];
    }
}

/* This is Controller:*/

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\CustomerImportRequest;
use App\Imports\ImportCustomers;
use App\Exports\ExportCustomers;
use Maatwebsite\Excel\Facades\Excel;
use DB;
use App\Customer;
use Illuminate\Support\Arr;

class ImportExportExcelController extends Controller
{
    protected $customers;

    public function __construct(Customer $customers){
        $this->customers = $customers;
    }

    public function index()
    {
        $customers = $this->customers->orderBy('id', 'desc')->get();
        return view('ImportExportExcel', compact('customers'));
    }

    public function importExcel(CustomerImportRequest $request)
    {
        try {

            if ($request->hasFile('import_file')) 
            {
                $file = $request->file('import_file');
                $columnRead = (new ImportCustomers)->toArray($file);
                
                
                $customerCheck = $this->customers->where('mobile',$columnRead[0][1]["mobile"])->first(); //**here not getting result, rather shows null**
                //dd($customerCheck);
                if($customerCheck)
                {
                    $customers = $customerCheck;
                    /* 
                    **How to update if duplicates are found and display old values updated. How to achieve this?**
                    */

                }else{
                    $customers = new $this->customers;
                    Excel::import(new ImportCustomers, $file);

                    return redirect()->back()->with('success','Data imported successfully.');
                }
                
            }

        } catch (\Maatwebsite\Excel\Validators\ValidationException $e) {
             $failures = $e->failures();
             //dd($failures);
             return redirect()->back()->with('import_errors', $failures);
             
        }
        
        
    }

    public function exportExcel()
    {
        $customers = Customer::select(["customer_name", "mobile", "email"])->get();  
        return Excel::download(new ExportCustomers($customers), 'customers.xlsx');
    }
}

/这是数据库迁移模式:/

public function up()
    {
        Schema::create('customers', function (Blueprint $table) {
            $table->id();
            $table->string('customer_name');
            $table->string('mobile', 13)->unique();
            $table->string('email')->nullable();
            $table->timestamps();
        });
    }

这里“mobile”是唯一的,所以如果像 customer_name 和 email 这样的值在具有相同手机号码的 excel 表中具有修改后的值。然后在导入时,应该更新值。 excel sheet

【问题讨论】:

    标签: laravel laravel-7 insert-update maatwebsite-excel laravel-excel


    【解决方案1】:

    我在 Laravel 6 中使用了 maatwebsite

    控制器 :

    Excel::import(new ImportCustomers(), $file);
    

    那么您可以在客户的 Import 类中应用您的逻辑:

    public function model(array $row)
    {
    try {
        $mobile =  $row[1]; //  referenced by row 
        $customer_name =  $row[0];
        $email = $row[1];
        $customer = Customer::where('mobile', $mobile)->first();
        //apply your logic
        if (!$customer) { // you may not need if else, if no customer exists then create a new record and assign mobile
            $customer = new Customer();
            $customer->mobile = $mobile;
        }
        $customer->customer_name = $customer_name;
        $customer->email = $email;        
        $customer->save();
        return $customer;
    } catch (Exception $ex) {
        dd($ex);
        return;
    }
    }
    

    另外请删除有关移动设备的规则,我认为这应该可行

    "*.mobile' => 'required'," 
    

    因为您的逻辑处理移动设备是独一无二的。

    【讨论】:

    • 感谢您的答复。现在,第一次记录导入工作正常,但如果我们再次上传相同的记录,则会显示类似警报 - 手机已被占用。
    • 请删除有关移动设备的规则,我认为这应该有效“*.mobile”=>“必需”,因为您的逻辑处理移动设备是唯一的。
    • 我很高兴听到这个消息,如果您现在发现它是正确的,我已经确定了我的答案。
    【解决方案2】:
    //Check for the existing value in database and if result is found do this.
     public function model(array $row)
        {
    
            // Check mobile already exists
            $count = Customer::where('mobile',$row['mobile'])->first();
           
           if($count){
              return;
           } 
        else{
            return new Customer([
                'customer_name' => $row['customer_name'],
                'mobile' => $row['mobile'],
                'email' => $row['email']
            ]);
           }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-20
      • 2021-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-15
      • 1970-01-01
      • 2020-12-31
      相关资源
      最近更新 更多