Below is a simplified version of my more complex problem. Changing the table structure is not an option.
I have a model called CostData
:
- My app can have “duplicates” of
CostData
that can later merge into one another (biz logic). - This is a parent / child relationship, where parent is the original
CostData
model and child is the duplicatedCostData
model.
The cost_data
table looks like so:
id | amount
1 2000.00
2 -1000.00
I have a model called MergeLink
:
- The
merge_links
table tells us howCostData
models (and many other unlisted models) should merge to one another.
The merge_links
table looks like so:
id | mergeable_type | parent_id | child_id
1 "AppModelCostData" 1 2
In Mergeable
trait used by CostData
model (and many other unlisted models), I have:
trait Mergeable
{
public function merge_link_parent(): MorphOne
{
return $this->morphOne(MergeLink::class, 'merge_link_parent', 'mergeable_type', 'child_id');
}
public function merge_link_children(): MorphMany
{
return $this->morphMany(MergeLink::class, 'merge_link_children', 'mergeable_type', 'parent_id');
}
}
This gives me back the correct MergeLink
when accessing merge_link_parent
or merge_link_children
on a CostData
model.
Now, I want to go one step further and return the mergeable_parent
or mergeable_children
relations, possibly using the merge_link_parent
and merge_link_children
relations respectively. See below Tinker pseudocode.
$costDataWithParent = AppModelCostData::find(2);
$costDataWithParent->mergeable_parent;
// Should return:
// {
// id: 1,
// amount: 2000,
// }
I would like to do this via a relation (not an accessor).