jeudi 29 décembre 2016

Laravel polymorthic relationship

I am trying to get my head around my first polymorphic relationship in Laravel 5.3.

The relationship i am trying to achieve is that an 'Editorial' will have many 'Elements' each element will be its own Model and have an order.

So for example i will have an 'ElementText', 'ElementImage', 'ElementButton' models then an 'Editorial' will have various elements assigned to it.

This is why i think i need a polymorphic relationship. I don't want multiple relationships for each element type in the 'Editorials' model, i want to be able to just get all 'Elements' regardless of its type and get it in order.

I think the idea solution would be to have an 'editorial_element' pivot table with columns like

editorial_id - integer
order - integer
element_id - integer
element_type - string

similar to the morphToManyexample in the laravel docs, but in that example you need to specify the model to morph.

So i also wondered if i should be using the morphTo() method in my Editorials model.

public function elements() {
    return $this->morphTo();
}

But i think that means i would have to add _type and _id columns to my editorials table which would be backwards (allowing one element per editorial)

Any idea if i can set the relationship i require up or am i approaching it wrong?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire