4 months ago

Eloquent; one model, relation to two models

Posted 4 months ago by NoxxieNl

Hiya all,

I have a legacy database and I am trying to build eloquent around it but I am a little stuck...

I have three tables:

  • Groups
  • Records
  • Attachments

The attachments table has two fields attachable_id and attachable_type. The attachable_id can contain a ID for Groups or for Records, with the attachable_type being either record or group.

How can I define a relationship on the attachments model to create a correct relationship for this? (Or two relationships for that).

I tried a where statement on the relation $this->hasMany(Group::class, 'attachable_id', 'id')->where('attachable_type', 'group'); though it fails cause it tries to get the column from the group model.

I have no clue how to do this... Does anyone can point me in the right direction?

Please sign in or create an account to participate in this conversation.