Reputation:
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.
Upvotes: 2
Views: 1761
Reputation: 969
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'));
Upvotes: 2
Reputation: 1028
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.
Upvotes: 1
Reputation: 4705
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' ));
Upvotes: 0
Reputation: 57648
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' ));
Upvotes: 0