Fetching via a join table as if it was a to-one relationship via Doctrine ORM

17 Views Asked by At

I'm trying to represent a "family" structure in a flexible manner where I can store all manner of links between two people, but primarily family relationships ("spouse", "parent", "child").

My drastically simplified schema:

I have a people table, simplified just to:

  • id [pk, auto inc]
  • forenames [varchar]
  • surname [varchar]

and a 'people_relationships' table:

  • id [pk, auto inc]
  • person_id [int]
  • relationship_id [int]
  • type ['spouse', 'parent', 'child', etc]

person_id and relationship_id both map to id on the person table. Two entries are stored in the person_relationships table, one for each direction. The above were created by the make:entity in Symfony, so I also have a fetchRelationships() method. All good so far.

However...

Given a person can only have one father and one mother, I'd like to be able to simply do:

<?php
$person->getFather(); // or getMother

which would resolve ONE instance of Person that would be the father or mother (or NULL if not set).

What I already think might work, but not quite what I'm after:

  1. I'm aware that I could add a father_id and mother_id on the person and literally maintain a one-to-one relation, and (via getters/setters) perhaps also keep an entry inside of person_relationships.
  2. I'm also aware that I could probably create these getters and just loop the results of getRelationships and return the one that matches. And the setters, too.

And so..

I just wondered whether there was a simpler way; with DQL or raw SQL, I could just add an extra condition on the JOIN such as type = "parent". I just don't see how this might be done via entity attributes/annotations. And from what I've read (and digested with my fairly limited knowledge of Doctrine) it doesn't appear to be possible.

And I'm also wondering whether I can ALSO do away with the need for storing each direction in the relationships table? In theory, I only need a type of 'parentchild' and then just use person_id as the parent, relationship_id as the child, etc.

Any help would be much appreciated!

0

There are 0 best solutions below