Files
2026-09-14 11:34:08 +08:00

84 lines
3.3 KiB
Python

from sqlalchemy.orm import Session
from model.stu_model import StuInfo
from model.cls_mgmt_model import ClsMgmt
from scheme.stu_scheme import StudentUpdate
class StudentDao:
"""查学生"""
#---------分页查询所有学生信息----------
@staticmethod
def get_all(db: Session, skip: int = 0, limit: int = 20):
return (db.query(StuInfo)
.filter(StuInfo.is_deleted == 0)
.offset(skip).limit(limit).all())
#---------根据学生id查询学生信息----------
@staticmethod
def get_by_id(db: Session, stu_id: str) :
return (db.query(StuInfo).
filter(StuInfo.id == stu_id)
.filter(StuInfo.is_deleted == 0)
.first())
#---------根据学生姓名查询学生信息----------
@staticmethod
def get_by_name(db: Session, stu_name: str) :
return (db.query(StuInfo)
.filter(StuInfo.name == stu_name)
.filter(StuInfo.is_deleted == 0)
.all())
#---------根据班级id查询班级学生信息----------
@staticmethod
def get_by_class(db: Session, cls_id: str) :
return (db.query(StuInfo)
.filter(StuInfo.cls_id == cls_id)
.filter(StuInfo.is_deleted == 0)
.all())
# """增加学生"""
# 1 ---------添加学生信息----------
@staticmethod
def create(db: Session, student_data: dict):
db_student=StuInfo(**student_data)
db.add(db_student)
db.commit()
db.refresh(db_student) # 刷新对象,获取数据库生成的默认值(如 created_at)
return db_student
# 2 ---------查询班级是否存在(可能班级创建了但还没人)----------
@staticmethod
def get_class_by_id(db: Session,cls_id:str):
return (db.query(ClsMgmt)
.filter(ClsMgmt.id==cls_id)
.first()) #不存在自动返回None
# 3 ---------查询对应的班级人数用来生成学号----------
@staticmethod
def count_by_class(db: Session, cls_id: str) -> int:
return (db.query(StuInfo)
.filter(StuInfo.cls_id == cls_id)
.filter(StuInfo.is_deleted == 0)
.count())
# """修改学生信息"""
#---------根据学生id查找并修改学生信息----------
@staticmethod
def update(db:Session,stu_id:str,stu_data:StudentUpdate):
db_student = StudentDao.get_by_id(db,stu_id)
if not db_student:
return None
# model_dump把用户传入修改请求体的信息转成字典,exclude_unset=True把没传入的字段排除掉,否则会None来修改其他字段
update_data = stu_data.model_dump(exclude_unset=True)
for key, value in update_data.items(): # 动态设置属性
setattr(db_student, key, value)
db.commit() # 提交事务
db.refresh(db_student) # 刷新对象,获取 onupdate 时间等
return db_student
# """删除学生信息""" 逻辑删除
#---------根据学生id查找并删除学生信息----------
@staticmethod
def delete(db:Session,stu_id:str):
db_student=StudentDao.get_by_id(db,stu_id)
if not db_student:
return False
db_student.is_deleted=1
db.commit()
db.refresh(db_student)
return db_student