我有一个名为的模型Lessons
,它与一个belongsToMany
名为. 课程模型为每节课都调用了字段。students
students_for_lesson
number_of_students
number_of_enrollments
我想要的是在number_of_enrollments
价值达到number_of_students
价值时发出一条消息,停止为课程添加学生。
我有一个名为的模型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.');
}
});
});