如何在MySQL / Laravel中建立“众多关系中的一个”关系

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

在开始讨论之前,我并不是在问一对多的关系。

我有一个名为enrollments的表,注册可以是lecturetestaptitude。表enrollmentslectures表,tests表和aptitudes表具有一对多的关系。

我的问题是:我该如何做到这一点,以使注册只能链接到这三个表之一?当前,数据库允许注册既是讲座又是考试,例如,这不可能。

问题的直观表示:enter image description here

我用Google搜索了好几个小时,但找不到任何有类似问题的人,请提供帮助。预先感谢。

php mysql database laravel relationship
2个回答
0
投票

由于注册只是三个中的一个,其他两个关系将为空,您不必担心它们。

假设某学生正在报名参加一次演讲,那么表行的test_id和aptitude_id的值为NULL,因此它们之间的关系为空。


0
投票

由于您使用的是laravel,这似乎是尝试使用多对一polymorphic relationship的好时机。

因此,想法是您的enrollments表将具有称为enrollable的关系,该关系可以指向3个表中的任何一个。注意:名称enrollable仅遵循laravel的示例命名约定。

要实现这种关系,您首先需要创建迁移,您可以在其中使用便捷的morphs方法,如下所示:>

// This will make 2 columns called 'enrollable_type' (VARCHAR) and 'enrollable_id' (UNSIGNED BIGINT)

Schema::table('enrollments', function (Blueprint $table) {
    ...
    $table->morphs('enrollable'); 
});

然后您只需要在模型中设置关系

// In the Enrollment model you define the enrollable relationship which will be either of 3 model

public function enrollable()
{
     return $this->morphTo('enrollable','enrollable_type','enrollable_id');
}

// in your 3 models you can specify the opposite relationship to refer back to the enrollment

public function enrollments()
{
     return $this->morphMany('App\Enrollment', 'enrollable', 'enrollable_type', 'enrollable_id');
}

正确设置后,您可以使用这种新关系,例如标准的一对多关系。例如$lecture->enrollments即可获得讲座的所有注册。

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