Laravel model with multiple submodels

  eloquent, laravel, laravel-7, php

I am building an application which has a quite complex model (at least for me). I’ve been looking for solutions for a few days now and still not sure I understand the correct way to write this.

I have a "main" model, which is named EscalationPolicy.
The policy can have targets (1 or many): Team, User or Schedule (can be 1 of each, or even multiple of each and none of some).

For sake of simplicity, let’s define the models as follow (Account is a parent model that owns multiple models with hasMany relation):

EscalationPolicy

account_id
name
"targets" (how to define this).

Team

account_id
name

User

account_id
name
email

Schedule

account_id
name
schedule_data (json)

What I am trying to achieve is to easily get the submodels from an EscalationPolicy, something like this:

$escalationPolicy = EscalationPolicy::find(1); //example
$targets = $ecalationPolicy->targets
//targets should be a collection of Team, User and Schedules associated to that policy.

I have tried to use polymorphic many-to-many relationship, but I am not able to have the correct output. Looking at the examples from Laravel’ documentation (Many To Many (Polymorphic)), I am not sure that is what I am trying to achieve, since I am not trying to use a single (Tag) model for multiple purpose (Post, Video) but rather have one model (EscalationPolicy) that can reference to multiple models (User, Team, Schedule).

Any idea if I can find a simple way to implement such thing?

Thanks a lot in advance,
ASM

Source: Laravel

Leave a Reply