例如,如何在Eloquent实体中建模此数据库层次结构,这样我就可以在创建汽车或卡车时自动创建汽车条目:
- automobile
id (PK)
color, etc...
- car
id (PK, automobile.id FK)
doors, etc...
- truck
id (PK, automobile.id FK)
axis, etc...
答案 0 :(得分:2)
您可以查看此关系http://laravel.com/docs/4.2/eloquent#polymorphic-relations
这些多态关系允许您对此用例进行建模。我不知道在创作时是否创建了汽车入口,但您可以自己轻松创建。希望这会有所帮助。
编辑:
要创建这样的关系,汽车表将获得两个新列,例如automobile_id
和automobile_type
,这些列的重要内容是后缀_id
和_type
。你的模型现在看起来像这样。
- automobile
id(PK)
color, etc...
automobile_id
automobile_type
- car
id(PK)
doors, etc...
在您的汽车类中,您现在将添加一个函数,该函数需要根据您在表格中选择的前缀来命名,在本例中为“汽车”:
<?php
class Automobile extends Eloquent {
...
public function automobile() {
return $this->morphTo()
}
}
当您创建新实体时,您将汽车的ID放入automobile_id = 1
,并为automobile_type
提供汽车雄辩模型的班级名称。在这种情况下,我认为它是Car
。对于创建工作流程,我建议您允许填写汽车和汽车的字段,然后首先将汽车实体输入数据库,检索列ID并将其填入automobile_id
。