首页 > 解决方案 > 关系限制 [ octobercms ]

问题描述

我有一个名为的模型Lessons,它与一个belongsToMany名为. 课程模型为每节课都调用了字段。studentsstudents_for_lessonnumber_of_studentsnumber_of_enrollments

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

标签: octobercmsoctobercms-pluginsoctober-partial

解决方案


一种方法是监听模型关系事件( BelongsToMany):beforeAttachafterAttachbeforeDetachafterDetach

在这种情况下,如果您需要在创建关系之前运行一些验证,请使用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 帖子和此处关于扩展模型的信息


推荐阅读