Vicc
Vicc

Reputation: 1

Doctrine|ORM|Symfony: Is possible relation to Interface or multiple entities

Simple example: I've got two users Admin and Client (both implements UserInterface) and Cart - three entity classes at a. Admin and Client can have his own carts. How to configure/resolve Cart entity relation to have method 'getUser()' which returns Admin or Client user?

Maybe I can have column user_id and second column with user entity name in Cart (something similar as DiscriminatorMapping can do)?

    class Admin implements UserInterface
    {

    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;
    
    /**
     * @var Collection
     * @ORM\OneToMany(targetEntity="Cart", mappedBy="???")
     */
    private $carts;
    ....
    class Client implements UserInterface
    {

    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;
    
    /**
     * @var Collection
     * @ORM\OneToMany(targetEntity="Cart", mappedBy="???")
     */
    private $carts;
    ....
    class Cart
    {

    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;
    
    /**
     * @var UserInterface
     * @ORM\ManyToOne(targetEntity="UserInterface", ???)
     */
    private $user;
    ....

I tried this Doctrine feature, also tried DisciminatorMapping and composite keys (join by multiple columns) option with no luck.

Any help?

Upvotes: 0

Views: 856

Answers (1)

user2403735
user2403735

Reputation: 181

I think you were almost there. DiscriminatorMapping is probably the way to go. However, you need to bind Client and Admin to a Parent class. So consider this hierarchy:

User (parent class)

  • Admin (extends User)
  • Client (extends User)

Then in your Cart entity you bind the relation to the User entity.

Upvotes: 2

Related Questions