在 Laravel database/model 设置中为需要不同列的关系使用的正确约定?

Right convention to use in Laravel database/model setup for relationships that needs different column's?

好吧,让我解释一下我想要什么

我应该有多个“用户”(ID、姓名、电子邮件...),每个用户应该有多个“account_types”(ID、姓名)中的 1 个。

设置起来似乎很简单,但棘手的部分来了。

每个“account_type”应该有不同的信息,然后我认为正确的方法是为每个“account_type”创建一个新的 table,其中包含每种类型所需的列但我不确定

让我用这个例子解释一下我想要什么:

Account types:  
ID: 1, Name: Private user 
ID: 2, Name: Company user 
.... More to be added ....

私人用户需要的信息应该是:

First name, Last name

但对于公司用户来说应该是:

Company name, Company identification number

我当然可以只将此信息存储在用户 table 中,使它们可以为空,然后根据“account_type”的内容输出所需的信息,但这似乎是错误的随着更多“account_types”的添加,可空选项将越来越大。此外,我需要根据“帐户类型”对我需要的信息进行硬编码,我认为这里使用的约定不正确?

我应该如何在 Laravel 中设置它? - 这里的正确约定是什么? - 如果我为每个“account_type”创建一个新的 table 是正确的,我将如何使用它(我是否需要为每个 table 创建一个模型,以及如何我要告诉 Laravel 使用正确的模型吗?

编辑

阅读 Anurat 的评论后(并感谢您引导我朝着正确的方向前进),我现在知道正确的方法是为每种帐户类型创建一个 table,然后为每个 table,然后我可以使用多态关系,但我仍然不确定它是如何工作的

我创建了以下迁移(每个迁移都有一个模型):

    Schema::create('account_types', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->timestamps();
    });

    Schema::create('private_account_infos', function (Blueprint $table) {
        $table->id();
        $table->string('first_name');
        $table->string('last_name');
        $table->timestamps();
    });

    Schema::create('firm_account_infos', function (Blueprint $table) {
        $table->id();
        $table->integer('cvr');
        $table->string('company_name');
        $table->timestamps();
    });

    Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->foreignId('account_type')->constrained()->cascadeOnDelete();
        $table->morphs('fillable');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });

这里我让 $table->morphs 出现在用户 table 上,但对吗? - 用户在 firm_account_infos 或 private_account_infos 中有信息,所以这就是为什么我将用户放在 table 中,但当我考虑它时,它应该是“account_types”如果用户可以在 firm_account_infos 或 private_account_infos 中获得信息,那么我需要在迁移中进行哪些更改才能使其正确?

我的理解是您不需要 account_types table,因为我们已经将不同类型的帐户拆分为 table,即私人和公司 table。私有中的所有记录都将具有相同的 account_type,公司中的所有记录也相同。

那么你可以和userstable.

建立一对一的多态关系
 privates ----|
              |----- users
 firms -------|

并且您需要添加到用户 table 架构

Schema::create('users', function (Blueprint $table) {
    $table->unsignedInteger('userable_id');
    $table->string('userable_type');
});

然后你在用户、私人和公司之间建立关系。

// User model

public function userable()
{
    return $this->morphTo();
}

// Private, Firm model

public function user()
{
    return $this->morphOne(User::class, 'userable');
}

当您想检索相关模型时,您可以

$user->userable;  // either private or firm

$private->user;
$firm->user;