关系限制[十月厘米]

时间:2019-03-26 11:18:59

标签: octobercms octobercms-plugins october-partial

我有一个名为 public String toString() { return this.Name + " " + this.Gender; } 的模型,它与一个名为Lessons的表具有一个belongsToMany的{​​{1}}关系。课程模型的每个课程都有名为studentsstudents_for_lesson的字段。

我要给的信息是停止发送,当number_of_students的值达到number_of_enrollments的值时添加学生。

1 个答案:

答案 0 :(得分:1)

一种方法是监听模型关系事件(BelongsToManybeforeAttachafterAttachbeforeDetachafterDetach

在这种情况下,如果您需要在创建关系之前运行一些验证,请使用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 post及此处有关extending models