#Two-sided polymorphic relationship

9 messages · Page 1 of 1 (latest)

swift flicker
#

Hey everyone, I'm looking for a way to create a two sided dynamic polymorphic relationship where I can attach different models to different other models. I can't use the default Polymorphic relationship since I won't know any of the model types. I have the following table structure, and I would like to have one global assignments table where all the relations are stored.

Models:

  • Contact
  • Company
  • Note
  • File
  • etc.

Basically every model should be assignable to every other model, so I would like to attach a note to a company and a contact, and a file to a note, but a file also to a company. And I do not wan't thousand tables notables, fileables, etc. I would like to have a table assignments with the fields (assignable_{type,id} and assigned_to_{type,id} but I'm not sure on how to do that with Eloquent

buoyant dune
#

why do you need this kind of relationship? Each of these relationships would most likely behave differently in your app so you shouldn't just group them into one mega relationship

swift flicker
#

Since I have many models like Note and File that can get attached to other different models, I thought that this could be the most easy way. How would you rather solve that, via own tables for each relation? So that you have notes and noteables, and the same for all files, etc.?

buoyant dune
#

yes thats the better way to go. then if you need to modify one relationship you don't have to worry about breaking all the other ones

#

code-wise you can keep things clean by using traits on your models like Noteable Fileable etc

swift flicker
#

And you would even go this way when you have like 6-8 models that can be related to 4 different kind of models? I'm just thinking about what's the best way to expand this logic in the feature. When using a global table I could also show all the relations in a chronologically order easily 🤔

buoyant dune
#

yes I would. why would you do that though? sounds like an unnecessary feature

swift flicker
#

Hm, thank you anyway. Found a way to do that, but not sure if i'm going to implement it that way.. For some kind of activity log to display when which note was created, file was uploaded, etc. That way I wouldn't have to fetch all the data and order them manually but already have them ordered, but for sure your way is the cleaner and probably easier-to-maintain one

buoyant dune