updateUserNo(); // 2. 给元和同事打标签 $this->tagYuanheColleague(); return $this->info('更新完成'); } /** * 批量更新学号 */ protected function updateUserNo() { $this->info('开始更新学号...'); $today = date('Y-m-d'); // 获取所有已开始且有学号前缀的课程 $courses = Course::with([ 'courseSigns' => function ($query) { $query->where('status', 1); } ])->whereNotNull('start_date') ->where('start_date', '<=', $today) ->whereNotNull('student_prefix') ->orderBy('start_date') ->get(); $totalUpdated = 0; foreach ($courses as $course) { $i = 1; // 编号前缀 foreach ($course->courseSigns as $sign) { $user = User::find($sign->user_id); // 只要用户没有学号(包括 null 和空字符串),都需要更新 if ($user->no) { continue; } // 生成学号,如果已存在则顺位+1继续尝试 $baseNo = $course->student_prefix . str_pad($i, 3, '0', STR_PAD_LEFT); $no = $baseNo; $attempt = 0; $maxAttempts = 1000; // 防止无限循环 // 检查学号是否已存在,如果存在则顺位+1继续尝试 while (User::where('no', $no)->where('id', '!=', $user->id)->exists() && $attempt < $maxAttempts) { $i++; $no = $course->student_prefix . str_pad($i, 3, '0', STR_PAD_LEFT); $attempt++; } if ($attempt >= $maxAttempts) { $this->warn('课程: ' . ($course->name ?? $course->id) . ', 用户: ' . ($user->name ?? $user->id) . ' 无法生成唯一学号,跳过'); continue; } // 更新用户编号 $user->no = $no; $user->save(); if ($no != $baseNo) { $this->info('课程: ' . ($course->name ?? $course->id) . ', 原学号: ' . $baseNo . ' 已存在,使用: ' . $no . ', 用户: ' . ($user->name ?? $user->id)); } else { $this->info('课程: ' . ($course->name ?? $course->id) . ', 学号: ' . $no . ', 用户: ' . ($user->name ?? $user->id)); } $i++; $totalUpdated++; } } $this->info('学号更新完成,共更新 ' . $totalUpdated . ' 个学号'); } /** * 给元和同事打标签 */ protected function tagYuanheColleague() { $this->info('开始给元和同事打标签...'); $tag = '元禾同事'; // 获取元和员工用户列表 $users = CourseSign::companyJoin(null, null, null, true, false); $count = 0; foreach ($users as $user) { // 获取当前的 from 字段 $from = $user->from ?? ''; // 将 from 字段按逗号分隔成数组 $fromArray = array_filter(array_map('trim', explode(',', $from))); // 检查是否已存在该标签 if (in_array($tag, $fromArray)) { continue; } // 追加标签 $fromArray[] = $tag; // 更新 from 字段 $user->from = implode(',', $fromArray); $user->save(); $this->info('已为用户 ' . $user->name . '(' . $user->mobile . ') 添加标签: ' . $tag); $count++; } $this->info('元和同事标签更新完成,共更新 ' . $count . ' 人'); } }