octobercms - 关系限制 [ octobercms ]
问题描述
我有一个名为的模型Lessons
,它与一个belongsToMany
名为. 课程模型为每节课都调用了字段。students
students_for_lesson
number_of_students
number_of_enrollments
我想要的是在number_of_enrollments
价值达到number_of_students
价值时发出一条消息,停止为课程添加学生。
解决方案
一种方法是监听模型关系事件( BelongsToMany
):beforeAttach,afterAttach,beforeDetach,afterDetach
在这种情况下,如果您需要在创建关系之前运行一些验证,请使用beforeAttach
事件:
LessonModel::extend(function ($model) {
/** Before Attach */
$model->bindEvent('model.relation.beforeAttach', function ($relationName, $attachedIdList, $insertData) use ($model) {
// Student => Lesson Relation
if ($relationName === 'your-lesson-student-relation-name') {
// Check Number of enrollments & other stuff ...
// throw new \ApplicationException('Cannot add student. Maximum number of enrollments reached.');
}
});
});
推荐阅读
- javascript - setInterval 不调用函数 Discord rpc
- sorting - 如何比较两个目录并将唯一的文件(名称或内容)移动到其他地方的第一个目录?
- python - 为什么我的 bot.get_user(user_id) 在 discord.py 中没有返回我?
- apache-superset - 为什么在 Apache Superset 中使用 SQL LAB 查询创建图表时会出现基本错误?
- python - 计算数据框中具有多列的成对行中的常见元素
- python - 减少 Google App Engine 部署时间?
- javascript - Javascript "+" 和 "-" 运算符的行为和用法
- postgresql - 使用 Prisma Migrate 运行集成测试时出错
- postgresql - 搜索 bigint 数组 posgreSQL 中是否存在任何子查询 bigint
- python - 为什么这会返回错误的最大值?