如何从Applicant模型创建Student并生成递增自定义注册编号
从Applicant模型生成Student并分配递增自定义注册编号
1. 先搞定Student模型和数据库表
首先创建Student模型和对应的数据库迁移,把Applicant里的核心字段同步过来,再加一个存储自定义注册编号的字段:
php artisan make:model Student -m
打开生成的迁移文件,补全字段(对应你Applicant模型的字段+注册编号):
public function up() { Schema::create('students', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email')->unique(); $table->string('phone'); $table->text('address'); $table->foreignId('department_id')->constrained(); $table->foreignId('course_id')->constrained(); $table->string('registration_number')->unique(); // 自定义注册编号,保证唯一 $table->timestamps(); }); }
执行迁移创建数据表:
php artisan migrate
2. 编写转换逻辑:把Applicant转成Student
方式一:在Applicant模型内添加转换方法
直接在Applicant模型里写一个方法,调用即可生成对应的Student记录:
// app/Models/Applicant.php public function convertToStudent() { // 生成递增注册编号,示例格式:STU-2024-0001 $latestStudent = Student::latest()->first(); $serialNumber = $latestStudent ? intval(substr($latestStudent->registration_number, -4)) + 1 : 1; $registrationNumber = 'STU-' . date('Y') . '-' . str_pad($serialNumber, 4, '0', STR_PAD_LEFT); // 创建Student并返回 return Student::create([ 'name' => $this->name, 'email' => $this->email, 'phone' => $this->phone, 'address' => $this->address, 'department_id' => $this->department_id, 'course_id' => $this->course_id, 'registration_number' => $registrationNumber, ]); }
使用时只需调用:$applicant->convertToStudent();
方式二:在控制器中处理审批转学生逻辑
如果是在审批申请环节完成转换,直接在控制器里写业务逻辑:
// app/Http/Controllers/ApplicantController.php public function approve(Applicant $applicant) { // 生成注册编号 $latestStudent = Student::latest()->first(); $serialNumber = $latestStudent ? intval(substr($latestStudent->registration_number, -4)) + 1 : 1; $registrationNumber = 'STU-' . date('Y') . '-' . str_pad($serialNumber, 4, '0', STR_PAD_LEFT); // 创建Student记录 Student::create([ 'name' => $applicant->name, 'email' => $applicant->email, 'phone' => $applicant->phone, 'address' => $applicant->address, 'department_id' => $applicant->department_id, 'course_id' => $applicant->course_id, 'registration_number' => $registrationNumber, ]); // 可选:标记Applicant为已通过状态 $applicant->update(['status' => 'approved']); return back()->with('success', '学生注册成功'); }
3. 优化:避免并发导致重复编号
如果存在多用户同时审批的场景,上面的逻辑可能生成重复编号,用数据库事务加锁解决:
DB::transaction(function () use ($applicant) { // 加锁防止并发读取同一序列号 $latestStudent = Student::lockForUpdate()->latest()->first(); $serialNumber = $latestStudent ? intval(substr($latestStudent->registration_number, -4)) + 1 : 1; $registrationNumber = 'STU-' . date('Y') . '-' . str_pad($serialNumber, 4, '0', STR_PAD_LEFT); Student::create([ // 同上字段 'registration_number' => $registrationNumber, ]); });
内容的提问来源于stack exchange,提问作者MAHMUD UMAR
相关产品推荐
相关产品推荐

