我该如何雄辩地定义多态逆多对多关系?

时间:2019-05-24 05:33:38

标签: laravel eloquent

我是Laravel的新手。关于雄辩的关系有些困惑。

我正在尝试实现这一目标:Relationship

这里是ER-Diagram

  • 1个问题可以是任何类型(多项选择/排序/匹配等)
  • 每个{type}表中的1个选项AKA只能映射到1个问题

在ER图中,红色突出显示的部分是我的第一个想法(多形1对多) 但现在我改为使用数据透视表将其更改为“多对五”:

[数据透视表]

question_id | choiceable_id | choiceable_type

但是,问题是:如何在模型中定义这种类型的关系?

  • 多态多对多类型是否正确?
  • 给定随机问题的正确答案是什么?

因为我了解这份文件。正确,我需要调用每种类型并在其中指定表,但我觉得这有点混乱...

// Question Model
function get_multiple_choices {
return $this->morphedByMany('App\TypeMultipleChoice', 'choiceable')

function get_ordering_choices {
return $this->morphedByMany('App\TypeOrderingChoice', 'choiceable')

...

此代码正确吗?而且我仍然不知道随机问题部分的选择。我觉得应该以一种更简单的方式来获得这些选择。

编辑

好吧,让我重新措辞。

我可以使用/如何使用:

// Question Model
function choices {
   // $this->MorphTo,MorphedByMany, etc. ?
}

代替

// Question Model
function get_multiple_choices {}
function get_matching_choices {}
function get_ordering_choices {}
... x 4-5 more times

1 个答案:

答案 0 :(得分:0)

使用“ hasMany”获得多对多关系

public function multipleChoices
{
    Return $this->hasMany('App\TypeMultipleChoice', 'choiceable');
}