[英]PHP / Laravel - One Model with multiple polymorphic relations
In my web app, users will be able to save some parsed content to a table called field_results
. 在我的Web应用程序中,用户将能够将一些已解析的内容保存到名为field_results
的表中。
However, this model needs to reference two polymorphic relationships: 但是,此模型需要引用两个多态关系:
FieldResults.php
: FieldResults.php
:
// A field result morphs to either a document field or email field.
public function fieldable()
{
return $this->morphTo();
}
// A field result morphs to either a document or email.
public function typeable()
{
return $this->morphTo();
}
The fieldable
refers to: 该fieldable
指的是:
and the typeable
refers to: 可typeable
是指:
In my DocumentField
and EmailField
models, I have defined this relationship: 在我的DocumentField
和EmailField
模型中,我定义了以下关系:
// A field will have a final result.
public function result()
{
return $this->morphOne(FieldResult::class, 'fieldable');
}
And in my Document
and Email
models, I have defined this: 在我的Document
和Email
模型中,我定义了以下内容:
public function results()
{
return $this->morphMany(FieldRuleResult::class, 'typeable');
}
So consider below loop, where I need to save some content, that will reference a specific documentfield/emailfield and a specific document/email. 因此,请考虑下面的循环,我需要在其中保存一些内容,该内容将引用特定的documentfield / emailfield和特定的document / email。
foreach ($document->fields as $field) {
$content = $field->content->text;
//Save the content to `FieldResult
$field->result()->create(['content' => $content]);
}
Above will only set the values for the fieldable
morph: 上面将仅设置可fieldable
变体的值:
SQLSTATE[HY000]: General error: 1364 : Field 'typeable_type' doesn't have a default value [...]
If I change it to save to the document instead, I get below error:: 如果我将其更改为另存为文档,则会出现以下错误:
//Save the content to `FieldResult
$document->result()->create(['content' => $content]);
SQLSTATE[HY000]: General error: 1364 Field 'fieldable_type' doesn't have a default value [...]
How can I do, so my model FieldResult
can have two polymorphic relationships? 我该怎么办,所以我的模型FieldResult
可以具有两个多态关系?
You can solve this problem by replacing this line: 您可以通过替换以下行来解决此问题:
$field->result()->create(['content' => $content]);
By the following lines: 通过以下几行:
$field->result()->create([
'content' => $content,
'typeable_id' => $document->id,
'typeable_type' => get_class($document),
]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.