StudentsImport.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace App\Imports;
  3. use App\Models\Course;
  4. use App\Models\Student;
  5. use App\Models\StudentCourse;
  6. use App\Models\StudentCourseTeacher;
  7. use App\Models\Teacher;
  8. use Carbon\Carbon;
  9. use Illuminate\Support\Facades\Log;
  10. use Illuminate\Support\Collection;
  11. use Maatwebsite\Excel\Concerns\ToArray;
  12. use Maatwebsite\Excel\Concerns\ToCollection;
  13. class StudentsImport implements ToArray
  14. {
  15. public function array(array $rows)
  16. {
  17. foreach($rows as $key => $row)
  18. {
  19. if($key == 0 || empty($row[0])) continue;
  20. $student = Student::firstOrCreate([
  21. 'name' => $row[0],
  22. 'phone' => $row[1]
  23. ], [
  24. 'remark' => $row[6]
  25. ]);
  26. if(empty($student)) continue;
  27. $course = Course::firstOrCreate([
  28. 'name' => $row[2]
  29. ]);
  30. if(empty($course)) continue;
  31. $assign_teacher = $row[5] == '全部' ? 1 : 2;
  32. $duration = null;
  33. if(!empty($row[3]) && !empty($row[4]) && $row[4] > $row[3]) {
  34. $duration = Carbon::createFromTimestamp(strtotime($row[3]))->diffInDays(Carbon::createFromTimestamp(strtotime($row[4])));
  35. }
  36. $student_course = StudentCourse::firstOrCreate([
  37. 'student_id' => $student->id,
  38. 'course_id' => $course->id
  39. ], [
  40. 'apply_date' => $row[3],
  41. 'duration' => $duration,
  42. 'assign_teacher' => $assign_teacher
  43. ]);
  44. if(empty($student_course)) continue;
  45. if($assign_teacher == 2) {
  46. $teacher_names = explode(',', $row[5]);
  47. foreach($teacher_names as $teacher_name) {
  48. $teacher = Teacher::firstOrCreate([
  49. 'name' => $teacher_name
  50. ]);
  51. StudentCourseTeacher::firstOrCreate([
  52. 'student_course_id' => $student_course->id,
  53. 'teacher_id' => $teacher->id,
  54. 'student_id' => $student->id,
  55. ]);
  56. }
  57. }
  58. }
  59. }
  60. }