oliverbusk
4 months ago

Multiple polymorphic relationship on one model

Posted 4 months ago by oliverbusk

In my web app, users will be able to save some parsed content to a table called field_results.

However, this model needs to reference two polymorphic relationships:

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:

  1. DocumentFields
  2. EmailFields

and the typeable refers to:

  1. Documents
  2. Emails

In my DocumentField and EmailField models, I have defined this relationship:

    // 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:

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.

     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:

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?

Please sign in or create an account to participate in this conversation.