Polymorphic relationship in doctrine 2

2019-04-08 15:34发布

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.

1条回答
Juvenile、少年°
2楼-- · 2019-04-08 16:22

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.

查看更多
登录 后发表回答