[DDC-1180] Indexed Associations: foreign key (association) cannot be used as indexBy field Created: 29/May/11  Updated: 01/Apr/14  Resolved: 01/Apr/14

Status: Resolved
Project: Doctrine 2 - ORM
Component/s: Mapping Drivers
Affects Version/s: 2.1
Fix Version/s: 2.4
Security Level: All

Type: Improvement Priority: Major
Reporter: Petr Sobotka Assignee: Benjamin Eberlei
Resolution: Fixed Votes: 3
Labels: None
Environment:

Using Doctrine ORM 2.1.0BETA1



 Description   

I am trying to index a collection by its entity's column which is also a foreign key (association). It seems to me that it is not possible at the moment.

For example:

/**
 * @Entity
 */
class Hotel
{

    // $id column and other stuff

    /**
     * @oneToMany(targetEntity="Booking", mappedBy="hotel", indexBy="room")
     * @var Booking[]
     */
    private $bookings;
}

/**
 * @Entity
 */
class Booking
{
    /**
     * @var Hotel
     *
     * @Id 
     * @ManyToOne(targetEntity="Hotel", inversedBy="bookings")
     * @JoinColumns({
     *   @JoinColumn(name="hotel_id", referencedColumnName="id")
     * })
     */
    private $hotel;

    /**
     * @var Room
     *
     * @Id
     * @ManyToOne(targetEntity="Room")
     * @JoinColumns({
     *   @JoinColumn(name="room_id", referencedColumnName="id")
     * })
     */
    private $room;
}

Only possible workaround I found is to define another (plain) entity's property mapped to the same table column and index by it:

/**
 * @Entity
 */
class Hotel
{

    // $id column and other stuff

    /**
     * @oneToMany(targetEntity="Booking", mappedBy="hotel", indexBy="roomId")
     * @var Booking[]
     */
    private $bookings;
}

/**
 * @Entity
 */
class Booking
{
    // ...

    /**
     * @var Room
     *
     * @Id
     * @ManyToOne(targetEntity="Room")
     * @JoinColumns({
     *   @JoinColumn(name="room_id", referencedColumnName="id")
     * })
     */
    private $room;
    
    /**
     * @var integer $roomId
     *
     * @Column(name="room_id", type="integer", nullable=false)
     */
    private $roomId;
}

Wouldn't it be easy to support it?



 Comments   
Comment by Benjamin Eberlei [ 05/Jun/11 ]

It is not so easy to implement from the first gimplse and it is not a bug but an improvement/feature request.

Comment by Benjamin Morel [ 02/Mar/13 ]

Related PR: https://github.com/doctrine/doctrine2/pull/204

Comment by Benjamin Morel [ 30/Mar/14 ]

This seems to have been integrated now:
https://github.com/doctrine/doctrine2/pull/639

Should this be marked as resolved?

Comment by Petr Sobotka [ 01/Apr/14 ]

Resolved. Thanks!

Generated at Sat Apr 19 17:10:46 UTC 2014 using JIRA 6.2.3#6260-sha1:63ef1d6dac3f4f4d7db4c1effd405ba38ccdc558.