2

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.

tshepang
  • 12,111
  • 21
  • 91
  • 136
  • I would consider making more room for different types images, what happens when your design changes and you need to provide a `image_profile_id`, or decides the image on the back never get any views so you might as well refactor it out? Sorry for being OT, just giving you a heads up :) – chelmertz Nov 16 '09 at 22:55

4 Answers4

2

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'));
Andrei Dziahel
  • 969
  • 5
  • 14
1

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
  • 1,018
  • 9
  • 7
0

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
  • 57,028
  • 9
  • 76
  • 100
0

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
  • 4,695
  • 6
  • 35
  • 56