Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymorphic relationship in doctrine 2

Is there a way to achieve the polymorphic relationship that Laravel have on doctrine?

Here is an example:

class Address
{
    protected $street;
    ...

    public function setStreet()
    {

    }

    public function getStreet()
    {

    }
}

class Event
{
    /*one to many*/
    protected $addresses;
    ...
}

class Museum
{
    /*one to many*/
    protected $addresses;
    ...
}

And on the database it would be something like this:

Address:
    id | type (event or museum) | type_id | street ...

Event:
    id | name ...

Museum:
    id | name ...

I looked at single table inheritance and it seems to solve my problem, but I did not understood how to associate the event or museum to the address. If someone could ELI5 I would be very grateful.

like image 258
Diego Castro Avatar asked Mar 18 '14 19:03

Diego Castro


1 Answers

It does look like a use case for inheritance mapping, unless you have a ton of different entities you want to store addresses for. Using your example in Doctrine, you'd create two classes for each of your addresses.

<?php
namespace MyProject\Model;

/**
 * @Entity
 * @InheritanceType("SINGLE_TABLE")
 * @DiscriminatorColumn(name="type", type="string")
 * @DiscriminatorMap({"event" = "EventAddress", "museum" = "MuseumAddress"})
 */
class Address {
    protected $street;
    // ...
}

/**
 * @Entity
 */
class EventAddress extends Address {
    protected $event;
    // ...
}

/**
 * @Entity
 */
class MuseumAddress extends Address {
    protected $museum;
    // ...
}

Read more about inheritance mapping.

like image 115
Peter Avatar answered Sep 25 '22 20:09

Peter