关系限制 [ 十月 CMS ]



我有一个名为Lessons的模型,它与一个名为students_for_lesson的表具有称为studentsbelongsToMany关系。课程模型具有每个课程的名为number_of_studentsnumber_of_enrollments的字段。

我想要的是当值达到number_of_students值时发出一条消息,停止为课程添加学生number_of_enrollments

一种方法是监听模型关系事件(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.');
        }
    });
});

请参阅此SO帖子和此处有关扩展模型的信息