关系限制[octobercms]

问题描述 投票:0回答:1

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

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

octobercms octobercms-plugins october-partial
1个回答
2
投票

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

在这种情况下,如果您需要在创建关系之前运行一些验证,请使用beforeAttachevent:

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 post&这里关于extending models

© www.soinside.com 2019 - 2024. All rights reserved.