Polymorphic Relations in Doctrine 2

Is there a way to achieve the polymorphic relationships that Laravel has 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 in the database it will be something like this:

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

Event:
    id | name ...

Museum:
    id | name ...

I looked at unidirectional inheritance and seemed to solve the problem, but I didn't understand how to associate an event or museum with an address. If someone could have ELI5, I would be very grateful.

+4
source share
1 answer

It looks like an example of use for inheritance, if you do not have tons of different objects for which you want to store addresses. Using your example in Doctrine, you will 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;
    // ...
}

More on inheritance .

+5
source

Source: https://habr.com/ru/post/1532356/


All Articles