study-api-v2/app/Models/Students/StudentClass.php

174 lines
3.7 KiB
PHP

<?php
namespace App\Models\Students;
use App\Models\BaseModel;
use App\Models\Schools\School;
use App\Models\Schools\SchoolClass;
use App\Models\Students\Student;
/**
* 学生班级关联模型
* @package App\Models\Students
* @property int $id 主键ID
* @property int $student_id 学生ID
* @property int $school_id 学校ID
* @property int $class_id 班级ID
* @property \Carbon\Carbon|null $join_time 入班时间
* @property \Carbon\Carbon|null $leave_time 离班时间
* @property int $status 状态(1正常在读2已转班3已毕业4退学)
* @property string|null $remark 备注
* @property \Carbon\Carbon $created_at 创建时间
* @property \Carbon\Carbon $updated_at 更新时间
*/
class StudentClass extends BaseModel
{
protected $table = 'student_class';
protected $fillable = [
'student_id',
'school_id',
'class_id',
'join_time',
'leave_time',
'status',
'remark',
];
protected $casts = [
'student_id' => 'integer',
'school_id' => 'integer',
'class_id' => 'integer',
'join_time' => 'datetime',
'leave_time' => 'datetime',
'status' => 'integer',
];
/**
* 状态常量
*/
const STATUS_NORMAL = 1; // 正常在读
const STATUS_TRANSFERRED = 2; // 已转班
const STATUS_GRADUATED = 3; // 已毕业
const STATUS_DROPOUT = 4; // 退学
/**
* 状态映射
*/
public static $statusMap = [
self::STATUS_NORMAL => '正常在读',
self::STATUS_TRANSFERRED => '已转班',
self::STATUS_GRADUATED => '已毕业',
self::STATUS_DROPOUT => '退学',
];
/**
* 关联学生
*/
public function student()
{
return $this->belongsTo(Student::class, 'student_id');
}
/**
* 关联学校
*/
public function school()
{
return $this->belongsTo(School::class, 'school_id');
}
/**
* 关联班级
*/
public function schoolClass()
{
return $this->belongsTo(SchoolClass::class, 'class_id');
}
/**
* 根据学生ID查询
*/
public function scopeByStudent($query, $studentId)
{
return $query->where('student_id', $studentId);
}
/**
* 根据学校ID查询
*/
public function scopeBySchool($query, $schoolId)
{
return $query->where('school_id', $schoolId);
}
/**
* 根据班级ID查询
*/
public function scopeByClass($query, $classId)
{
return $query->where('class_id', $classId);
}
/**
* 根据状态查询
*/
public function scopeByStatus($query, $status)
{
return $query->where('status', $status);
}
/**
* 查询正常在读的学生
*/
public function scopeNormal($query)
{
return $query->where('status', self::STATUS_NORMAL);
}
/**
* 查询未离开的学生
*/
public function scopeNotLeft($query)
{
return $query->whereNull('leave_time');
}
/**
* 获取状态名称
*/
public function getStatusNameAttribute()
{
return self::$statusMap[$this->status] ?? '未知状态';
}
/**
* 检查是否正常在读
*/
public function isNormal()
{
return $this->status === self::STATUS_NORMAL;
}
/**
* 检查是否已离开
*/
public function hasLeft()
{
return !is_null($this->leave_time);
}
/**
* 获取在读时长(天数)
*/
public function getStudyDays(): int
{
if (!$this->join_time) {
return 0;
}
$endTime = $this->leave_time ?? now();
return $this->join_time->diffInDays($endTime);
}
}