【发布时间】:2021-11-14 05:40:47
【问题描述】:
我正在开发一个带有子域的 Laravel 项目。每个新公司都有自己的子域。在公司内部创建的每个客户都需要获得相同的子域。
因为子域可能会随着时间而改变,所以我正在使用子域表。
所以我有三个表和模型:Subdomain、Company 和 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
虽然我在 Laravel 文档中找到了$table->morphs('organisation');,但我将其更改为
$table->bigInteger('organisation_id')->unsigned()->nullable();
$table->string('organisation_type')->nullable();
这可以创建子域和公司条目,但公司表中的 subdomain_id 列为 NULL。
我做错了什么?
【问题讨论】:
-
问题在于您的关键约定
标签: laravel relationship