laravel - 多态一对多关系为NULL
问题描述
我正在开发一个带有子域的 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
虽然我$table->morphs('organisation');
在 Laravel 文档中发现我将其更改为
$table->bigInteger('organisation_id')->unsigned()->nullable();
$table->string('organisation_type')->nullable();
这可以创建子域和公司条目,但subdomain_id
公司表中的列是 NULL。
我做错了什么?
解决方案
'enterprise_number' => 应该是模型 id ex: 1
,
'legal_entity_type' => 应该是模型命名空间 ex: 'App\Models\ModelName'
,
推荐阅读
- f# - 预期如何断言异常
- r - 线性回归的置信区间
- .htaccess - 带有 2 个参数的网址/在 .htaccess 中重写
- r - 显示 R 函数列表,因此您不会窃取已使用的名称
- java - 如何让 Guice 正确绑定这个泛型?
- rest - 如何符合 REST url 模式而不是方法名称
- isabelle - Isabelle/HOL:在另一个语言环境中访问解释
- ruby-on-rails - 如何从下拉列表中传递选定的值并将其作为参数访问以在 Rails 中级联下拉列表
- javascript - TinyMCE:编辑器中的中心对话框窗口 (WindowManager.open)
- javascript - 将对象数组转换为键值数组