首页 > 解决方案 > 多态一对多关系为NULL

问题描述

我正在开发一个带有子域的 Laravel 项目。每个新公司都有自己的子域。在公司内部创建的每个客户端都需要获得相同的子域。

因为子域可能会随着时间而改变,所以我正在使用子域表。

所以我有三个表和模型:SubdomainCompany以下Client规则:

因此我使用多态的一对多关系。

create_subdomains_table 迁移

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

create_companies_table 迁移

Schema::create('companies', function (Blueprint $table) {
    $table->id();
    $table->string('enterprise_number')->unique();
    $table->string('legal_entity_type');
    $table->string('business_name');
    $table->string('phone');
    $table->string('email');
    $table->json('ancestry')->nullable();
    
    $table->bigInteger('subdomain_id')->unsigned()->nullable();
    $table->foreign('subdomain_id')->references('id')->on('subdomains');

    $table->timestamps();
});

公司模式

public function subdomain() {
    return $this->morphOne(Subdomain::class, 'organisation');
}

子域模型

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

创建公司控制器功能

// Create subdomain
$subdomain = Subdomain::create([
    'name' => Str::slug($validatedData['business_name'], '-')
]);

// Create company
$company = Company::create([
    'enterprise_number' => $validatedData['enterprise_number'],
    'legal_entity_type' => $validatedData['legal_entity_type'],
    'business_name' => $validatedData['business_name'],
    'phone' => $validatedData['phone'],
    'email' => $validatedData['email'],
]);

// Create relationship between company and subdomain
$company->subdomain()->save($subdomain);

这会导致错误Not null violation: 7 ERROR: null value in column \"organisation_type\" of relation \"subdomains\" violates not-null constraint

虽然我$table->morphs('organisation');在 Laravel 文档中发现我将其更改为

$table->bigInteger('organisation_id')->unsigned()->nullable();
$table->string('organisation_type')->nullable();

这可以创建子域和公司条目,但subdomain_id公司表中的列是 NULL。

我做错了什么?

标签: laravelrelationship

解决方案


'enterprise_number' => 应该是模型 id ex: 1,
'legal_entity_type' => 应该是模型命名空间 ex: 'App\Models\ModelName',


推荐阅读