修改扩展模型的数据库

时间:2018-03-14 07:54:21

标签: database laravel extend

我遇到这种情况:

我有Person的表格(称为persons)。一个人有姓名,身份证和类型(自然或法律)。 然后我Organization,它当然是一个法人,延伸Person并具有manager_idemployees等特定字段。 然后我有Authority这是一个特殊政府Organization,所以最后也是Person,还有decree_number等特殊必填字段(数字和年份)构成Authority)的法令。

然后我有了我的数据库,我有一个名为persons的表。

我的问题是:我应该为organizations创建一个新表,然后为authorities创建另一个表吗?如果没有,我应该如何存储当局或组织所需的新字段,而不是人员?

我在Laravel项目中这样做,我可以:

/* Person.php */
class Person extends Model {
}

/* Organization.php */    
class Organization extends Person {
    protected $table = 'persons';
}

/* Authority.php */    
class Authority extends Organization {
    protected $table = 'persons';
}

1 个答案:

答案 0 :(得分:0)

是创建另一个表但不重复persons已有的数据,您可以只使用它的关系。

例如,创建一个名为organizations的表,用于存储组织级别的人员。架构可以是:

| person_id (FK to persons.id) | manager_id | other_fields |

然后是authorities的另一个表,用于存储authority级别的人员。架构可以是:

| person_id (FK to persons.id) | decree_number | other_fields |

然后在Laravel,创建一个关系,我在这里假设一对一的关系。

// Person.php

public function organizationProfile()
{
    return $this->hasOne(Organization::class);
}

public function authorityProfile()
{
    return $this->hasOne(Authority::class);
}

public function hasOrganization()
{
    return $this->organizationProfile !== null;
}

public function hasAuthority()
{
    return $this->authorityProfile !== null;
}

设计就像Person可以有个人资料(在您的情况下是组织权限)。可能还有其他设计,但这就是我所想到的。

总之,由于 Organization Authority 都是 Person ,只有另一个属性,我们只创建了另一个表来保存这些属性但是不要重复 Person 中已存在的属性。我们将利用关系来确定 Person 只是 Person Organization 授权