oliverbusk
5 months ago
50
13
Laravel

Advanced relationship in Laravel

Posted 5 months ago by oliverbusk

In my web application, users can upload documents or emails to channels.

A channel can furthermore then have document_tags and email_tags, that all uploaded documents/emails automatically should inherit.

Furthermore, document_tags and email_tags will have different descriptions: tag_descriptions. So for example if we have a document, uploaded to a channel that have the tags: animals (id = 1) and pets (id = 2)

  1. Document #55 is upladed to Channel #8.
  2. Document #55 will automatically inherit the tags, that have document_tags.channel_id = 55 (this can be accessed with the following relationship: $channel->documenttags). In this case animals and pets.
  3. Now the user should be able to set an unique description for the tegs animals and pets in tag_descriptions, for example:

tag_descriptions

id | taggable_type   | taggable_id  | typeable_type | typeable_id | description
1  | App\DocumentTag | 1            |  App\Document | 55          | My unique description for animals. 
2  | App\DocumentTag | 2            |  App\Document | 55          | My unique description for pets.

Now in above database design the uploaded document #55, have the tags: animals and pets associated, but further these two tags have a unique description, that is unique for the specific document.

If I upload another document, or an email (let's say email #20), then I imagine it will look like:

tag_descriptions:

id | taggable_type   | taggable_id  | typeable_type | typeable_id | description
1  | App\DocumentTag | 1            |  App\Document | 55          | My unique description for animals. 
2  | App\DocumentTag | 2            |  App\Document | 55          | My unique description for pets.
3  | App\EmailTag    | 1            |  App\Email    | 20          | Another unique description for animals. 
4  | App\EmailTag    | 2            |  App\Email    | 20          | Yet another unique description for pets.

Now the email #20 also have the tags animals and pets, but in this case, the user can set unique descriptions for the tags.

Now my question is:

Is above design doable, and is it considered best practice in Laravel / PHP? I am a bit unsure how to structure the code, because the TagDescription model will suddenly have two polymorphic relationships (taggable and typeable), and I cannot find anything in the documentation that this is supported.

Furthermore, I am unsure if I can use the above design to access the unique descriptions through the specific uploaded document, such as:

//In my Document.php model:
public function tagdescriptions()
{
    return $this->morphMany(TagDescription::class, 'typeable');
}

Then use it like: $document->tagdescriptions.

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