2
votes

I have a Laravel model called "Area" which contains "Elements". Elements can be different Models (in this case a FreetextElement and a CheckboxElement). The whole thing is hooked up with a polymorphic pivot table, which contains the area_id, the element_id and the element_type. The basic relationship works fine. If I for example say:

$area->freetextElements 

Then I get all the freetextElements that are attached to that particular area. My issue is that I'd like a relationship function, which gets all the elements that are attached to the area, regardless of their model.

Here are the areas relations:

public function freetextElements()
{
    return $this->morphedByMany(ElementFreetext::class, 'element', 'coaching_element_area_element');
}

public function checkboxElements()
{
    return $this->morphedByMany(ElementCheckbox::class, 'element', 'coaching_element_area_element');
}

//find a better solution for this
public function elements()
{        
    return array_merge( $this->freetextElements->all(), $this->checkboxElements->all());
}

The last function "elements" is just to illustrate what I'm trying to achieve.

Any suggestions? Thanks in advance.

Best Regards

1

1 Answers

0
votes

So I have found a solution to this issue. It's not the cleanest solution. So I'm still open to any additional feedback, but I thought I leave this here for other people.

I simply created a model for the pivot table entries. Area->Elements is the relationship to the pivot table entries and That pivot table model is related to the individual elements via it's own relation. Now I can chain the relation by saying: Area->Elements->Element. It's not optimal, but it gets the job done.