Ondrej Slinták
Ondrej Slinták

Reputation: 31910

Doctrine entity as default value in another entity

In following example, I'd like the default value for $usergroup to be 1. Obviously, I cannot set it to 1 as it expects an Usergroup object.

/**
 * @var integer $usergroup
 *
 * @ORM\ManyToOne(targetEntity="Usergroup")
 */
private $usergroup;

Is it possible to somehow set it to Usergroup object with id of 1 or should I handle it when I'm actually persisting the object?

Upvotes: 2

Views: 522

Answers (1)

Arnaud Le Blanc
Arnaud Le Blanc

Reputation: 99911

You should have a service for creating new YourEntity instances. The service will know of to retrieve the default group, or how to create a reference to the default group, and will take care of passing it to the entity's constructor.

For example:

class YourEntityService
{
    ...

    public function createNewYourEntity()
    {
        $defaultGroup = $this->em->getReference('Usergroup', 1);
        return new YourEntity($defaultGroup);
    }

    ...
}

Upvotes: 5

Related Questions