views:

762

answers:

4

Just working on a project where I have a class called 'Product' and a class called 'Image'. Each product has two types of images, one 'front' image and one 'back' image, so I defined two fields, one called image_front_id and one called image_back_id.

In the method BaseProduct::setUp(), I defined the relation for the front images as follows:

$this->hasOne( 'Image', array ('local' => 'image_front_id', 'foreign' => 'id' ) );

Now, obviously, when I define another 'hasOne' to the class 'Image', but now with the local fieldname of 'image_back_id', this doesn't work right. So my question is: how can I define multiple 'one-to-one' relations to the same class? I've been searching for this for some time now, but I can't seem to find it.

A: 

If I remember correctly, the first parameter is the name of the reference, and the referenced class is given by the refClass property:

$this->hasOne('FrontImage', array('local' => 'image_front_id', 'foreign' => 'id', refClass => 'Image' ));
$this->hasOne('BackImage', array('local' => 'image_back_id', 'foreign' => 'id', refClass => 'Image' ));
Zed
You do not need `refClass` in regular 1to1 relation
develop7
How would Doctrine know that BackImage relation refers to the Image class then?
Zed
I think that would be just `class`
Swanand
A: 

I believe the solution is as follows (using the 'as' keyword):

$this->hasOne('Image as FrontImage', array('local' => 'image_front_id', 'foreign' => 'id', refClass => 'Image' ));
$this->hasOne('Image as BackImage', array('local' => 'image_back_id', 'foreign' => 'id', refClass => 'Image' ));
Arthur Frankel
+1  A: 

Zed's answer works if you have 2 different tables that you are trying to relate to, but it sounds like you are trying to relate both fields to the same table. Arthur Frankel's solution should work for you. You can't have multiple relationships with the same name, so you have to use aliases to get 2 different relationships to the same Image table. By declaring 'Image as FrontImage' and 'Image as BackImage', each relationship has its own alias.

Thomas Albright
+2  A: 

The right answer is

$this->hasOne('Image as FrontImage', array('local' => 'image_front_id', 'foreign' => 'id'));
$this->hasOne('Image as BackImage', array('local' => 'image_back_id', 'foreign' => 'id'));
develop7
This is the right way.
Swanand