Tuesday, April 19, 2011

Multiple Doctrine relations on the same table

From: http://www.odino.org/231/multiple-doctrine-relations-on-the-same-table


Using symfony with Doctrine if you have a model which is related to another mdoel you're used to write stuff in the schema like this:

Model_1:
  columns:
    model_2_id:  ...
  relations:
    Model_2:
      local:     model_2_id
      foreign:  id

which works perfectly unless you specify that another column is related to Model_2 in the same way of the first:

Model_1:
  columns:
    model_2_id:         ...
    model_2_second_id:  ...
  relations:
    Model_2:
      local:     model_2_id
      foreign:  id
      alias:     FirstModel2
    Model_2:
      local:     model_2_second_id
      foreign:  id
      alias:     SecondModel2 

This messes things up because, as sfYaml converts YAML to plain PHP array, 2 elements have the same key ( Model_2 ) and the resulting SQL will create one relation instead of 2.
The solution is simple ( this is a silly error, I often forget it due to the lack of attention ), you only need to extract the alias and specify the class for each relation:

Model_1:
  columns:
    model_2_id:         ...
    model_2_second_id:  ...
  relations:
    FirstModel2:
      class:     Model2
      local:     model_2_id
      foreign:  id
    SecondModel2:
      class:     Model2
      local:     model_2_second_id
      foreign:  id

I also noticed that you can magically use a single relation ( but without the possibility, I suppose, to specify custom aliases [ not sure about this ] ):

Model_1:
  columns:
    model_2_id:         ...
    model_2_second_id:  ...
  relations:
    Model2:
      local:     [model_2_id, model_2_second_id]
    foreign:  id

This one is normally pretty useless ;-)

0 评论:

Post a Comment