123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- <?php
- namespace App\Imports;
- use App\Models\Course;
- use App\Models\Student;
- use App\Models\StudentCourse;
- use App\Models\StudentCourseTeacher;
- use App\Models\Teacher;
- use Carbon\Carbon;
- use Illuminate\Support\Facades\Log;
- use Illuminate\Support\Collection;
- use Maatwebsite\Excel\Concerns\ToArray;
- use Maatwebsite\Excel\Concerns\ToCollection;
- class StudentsImport implements ToArray
- {
- public function array(array $rows)
- {
- foreach($rows as $key => $row)
- {
- if($key == 0 || empty($row[0])) continue;
- $student = Student::firstOrCreate([
- 'name' => $row[0],
- 'phone' => $row[1]
- ], [
- 'remark' => $row[6]
- ]);
- if(empty($student)) continue;
- $course = Course::firstOrCreate([
- 'name' => $row[2]
- ]);
- if(empty($course)) continue;
- $assign_teacher = $row[5] == '全部' ? 1 : 2;
- $duration = null;
- if(!empty($row[3]) && !empty($row[4]) && $row[4] > $row[3]) {
- $duration = Carbon::createFromTimestamp(strtotime($row[3]))->diffInDays(Carbon::createFromTimestamp(strtotime($row[4])));
- }
- $student_course = StudentCourse::firstOrCreate([
- 'student_id' => $student->id,
- 'course_id' => $course->id
- ], [
- 'apply_date' => $row[3],
- 'duration' => $duration,
- 'assign_teacher' => $assign_teacher
- ]);
- if(empty($student_course)) continue;
- if($assign_teacher == 2) {
- $teacher_names = explode(',', $row[5]);
- foreach($teacher_names as $teacher_name) {
- $teacher = Teacher::firstOrCreate([
- 'name' => $teacher_name
- ]);
- StudentCourseTeacher::firstOrCreate([
- 'student_course_id' => $student_course->id,
- 'teacher_id' => $teacher->id,
- 'student_id' => $student->id,
- ]);
- }
- }
- }
- }
- }
|