0

I have two fields : account_type_id and account_id. How can i manually map doctrine TargetEntity to join Company Entity if accountTypeId = 1 OR join User Entity if account_type_id = 2 ?

<?php 
/** @Entity */
class Accounts
{
    // 1= Company, 2 = User
    private $accountType;

    /**
     * @ManyToOne(targetEntity="Companies")
     */
    private $company;


    /**
     * @ManyToOne(targetEntity="Users")
     */
    private $user;

    //...

}
yivi
  • 42,438
  • 18
  • 116
  • 138
Titeufggg
  • 21
  • 3

1 Answers1

1

Unfortunately, joining different columns on the fly cannot be done automatically, but you can have both fields set as nullable and only set the correct one when persisting the Account entity.

This would be the annotation:

/**
 * @ORM\ManyToOne(targetEntity="Users", inversedBy="users")
 * @ORM\JoinColumn(name="user_id", referencedColumnName="id", nullable=true)
 */
private $user;

Keep in mind that nullable=true is the default anyway, I'm just being specific here.

If you want to go defensively about this, you can have an additional check in getter

/**
 * @return User
 * @throws \Exception
 */
public function getUser()
{
    if ($this->accountType !== 2) {
        throw new \Exception("Entity is not of type 'user'");
    }
    return $this->user;
}