[英]Complex Laravel Relationships
I am facing some problems on how to set up my tables/relationships in laravel. 关于如何在laravel中设置表/关系,我遇到了一些问题。
Description: A user can have 3 types (tenant, manager, admin). 描述:用户可以有3种类型(租户,经理,管理员)。 The admin is the easiest type, it has no extra properties.
admin是最简单的类型,它没有额外的属性。 Tenants and Managers have extra properties pertaining to each type.
租户和经理拥有与每种类型相关的额外属性。 Furthermore, a tenant has a 1-1 relationship to a unit (assuming for now 1 user account per unit) and a manager has a NN relationship with the properties (multiple managers can manage 1 property and 1 manager can manage multiple properties).
此外,租户与单元的关系为1-1(假设现在每个单元有1个用户帐户),并且管理员与属性具有NN关系(多个管理员可以管理1个属性,1个管理员可以管理多个属性)。
What I came up with so far: 到目前为止我想出了什么:
User has a polymorphic relationship and belongs to both the tenant and manager. 用户具有多态关系,属于租户和经理。
How my model relationships would be set up: 如何建立我的模型关系:
User.php
public function subaccount()
{
return $this->morphTo('subaccount');
}
Manager.php
and Tenant.php
Manager.php
和Tenant.php
public function user()
{
return $this->morphOne(User::class, 'subaccount');
}
Pros: 优点:
Cons: 缺点:
Both tenant and manager would belong to the user 租户和经理都属于用户
How my model relationships would be set up: 如何建立我的模型关系:
Manager.php
and Tenant.php
these are fine Manager.php
和Tenant.php
这些都很好
public function user()
{
return $this->belongsTo(User::class);
}
User.php
would need something like this User.php
需要这样的东西
public function subaccount()
{
if ($this->type === 'tenant') {
$resource = Tenant::class;
} else if ($this->type === 'manager') {
$resource = Manager::class;
}
return $this->hasOne($resource);
}
Pros: 优点:
Cons: 缺点:
Would love to get different perspectives on this or thoughts on any other way I can build this. 我希望能够对此有不同的看法,或者想要以其他任何方式构建这个。
If you think about what makes a User a Tenant, you'll probably find that the only thing is their relationship with a Unit. 如果你考虑一下什么使用户成为租户,你可能会发现唯一的问题是他们与一个单位的关系。 In isolation, a Tenant is just a User if they have no Unit.
孤立地,如果租户没有单位,他就是用户。
Therefore: 因此:
class User {
public function Tenancy() {
return $this->hasOne(Tenancy::class);
}
}
...
class Tenancy {
public function Unit() {
return $this->belongsTo(Unit::class);
}
}
Similarly, your Manager is only a Manager because he/she manages multiple properties. 同样,您的经理只是经理,因为他/她管理多个房产。 Therefore, you'll need a many-many relationship between the User and Property, with the details of the relationship on the pivot.
因此,您需要在用户和属性之间建立多对多关系,并在枢轴上显示关系的详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.