【问题标题】:Laravel - Update a table using Maatwebsite Excel Import based on conditionLaravel - 根据条件使用 Maatwebsite Excel 导入更新表格
【发布时间】:2021-03-09 08:51:52
【问题描述】:

使用 Laravel-5.8 和 Maatwebsite-3.1,我有一个表叫做雇员(Employee)。

class FirstEmployeeSheetImport implements ToModel, WithBatchInserts, WithHeadingRow, SkipsOnError, WithValidation, SkipsOnFailure
{
   use Importable, SkipsErrors, SkipsFailures;

   public function model(array $row)
   {           
      $this->department = $row['department'];        
      $employee_data = [
        'employee_code'                     => $row['employee_code'],
        'company_id'                        => Auth::user()->company_id,
        'email'                             => $row['official_email'],
        'department_id'                     => $this->getDepartment(),
     ];                
     $employee = Employee::create($employee_data);                   
   }

   public function getDepartment(){
    if(!empty($this->department) || !$this->department){

        return HrDepartment::where('dept_name',$this->department)->where('company_id',Auth::user()->company_id)->pluck('id')->first();
    } else {
        return 0;
    }
  }              
}

我想使用 excel 上传来更新这两 (2) 个字段:每个员工的电子邮件和部门 ID,其中:

company_id = Auth::user()->company_id AND employee_code = $row['employee_code']。

此外,它应该只对满足条件的人执行更新。我应该只执行更新而不是克里特。

我如何做到这一点?

谢谢

【问题讨论】:

  • ToModel 会自动插入数据库,请使用 ToCollection 或 ToArray 代替
  • @AnuratChapanond - 我该如何实现?请向我展示我的代码中的示例。谢谢

标签: laravel maatwebsite-excel


【解决方案1】:

您可以使用ToCollection 将您的数据导入$rows,然后相应地更新您的数据。

class FirstEmployeeSheetImport implements ToCollection
{
    public function collection(Collection $rows)
    {
        foreach ($rows as $row) 
        {
            Employee::where('company_id', auth()->user()->company_id)
                ->where('employee_code', $row['employee_code'])
                ->update([
                    'email' => $row['email'],
                    ...
                ]);
        }
    }
}

【讨论】:

    猜你喜欢
    • 2021-10-08
    • 2020-12-20
    • 2022-12-31
    • 2019-05-20
    • 2020-08-28
    • 1970-01-01
    • 1970-01-01
    • 2020-07-09
    • 1970-01-01
    相关资源
    最近更新 更多