lundi 24 juillet 2017

How to get a related model through a pivot table in Laravel?

i have a bit of a problem in my Laravel 5.4 application, in my database i have several entities that are related through a central model called Content like such.

Actor     -> actors_contents     -> Content
Category  -> categories_contents -> Content


And then i have three other entities that are "contents" like Video, Photo etc...

Video (content_id)  -> Content
Photo (content_id)  -> Content
Stream (content_id) -> Content

What i want is to be able to, for instance access all of the Videos for a particular Actor from the Actor model, while also being able to directly get the Actors inside of the Video Model.

So essentially, get the content_id for the current Actor from a pivot table and then find the Videos that match it.

I was trying to use hasManyThrough but after reading for a while i found that it doesn't work with Many-to-many relationships, so my question is how can i make this work otherwise? I don't want to have to define my own Relationships or anything like that, i could i guess create a method on the Model that simply does some joins to get the values i want, but does that have implications behind the scenes when compared to Laravel's Relationships?

For one

 ->with(['relation'])

Would no longer work with this relationship and as such i wouldn't be able to eager load it and that might be a bit of a problem, so how would you guys solve this problem? Thank you in advance for your help.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire