user742736
user742736

Reputation: 2729

Symfony - Get Entity from within another entity

I would like to retrieve a record from another entity (or record from the DB) within a entity.

They there are no relationship between the two entities.

I am using @ORM\HasLifecycleCallbacks() and @ORM\PrePersist so when the main entity is created it will also create another entity (save a record to another table)

The above is working fine, there are no issues with this.

What I am having an issue with is I would like to link that entity with another table but I need to retrieve the object based on the value of the first entity.

Usually I would write a function in the entity repository but I am not calling the entity manager within the entity.

Upvotes: 2

Views: 8041

Answers (3)

Steffen Kamper
Steffen Kamper

Reputation: 172

In Symfony 3.1 you can use the entityManager to set a reference. This is still lightweight as it does not instance a complete Doctrine Record.

Example: I have an entity Status which has some states, and it's referenced in another entity. On create i use this method inside EventSubscriber:

public function preAction(LifecycleEventArgs $args)
{
    $entity = $args->getObject();
    $entityManager = $args->getObjectManager();

    if (method_exists($entity, 'setStatus')) {
        if ($entity->getStatus() === null) {
            $entity->setStatus($entityManager->getReference('AppBundle\Entity\Status', Status::STATUS_REGULAR));
        }
    }
}

Upvotes: 0

TazGPL
TazGPL

Reputation: 3748

Entity manager is accessible in an entity repository. You can legally use it to fetch data from other entities and to compose your business logic. This is what entity repositories are made for: Doctrine Custom Repositories, Symfony Custom Repository Classes.

/**
 * @ORM\Entity
 */
class Beta {}

/**
 * @ORM\Entity
 */
class Alpha {}

class AlphaRepository extends EntityRepository
{
    public function getDataFromAnotherEntity($something)
    {
        $query = 'select * from MyBundle\Entity\Alpha alpha where alpha.id = :something';
        return $this->getEntityManager()
            ->createQuery($query)
            ->setParameter('something', $something)
            ->getResult();
    }
}

Upvotes: 0

Diego Ferri
Diego Ferri

Reputation: 2787

An Entity in Doctrine is an object representation of a concept, with attributes and methods. It is meant to be lightweight, a POPO (plain old php object). It must not know anything about its persistence. Therefore if you see reference to the EntityManager in a model, it probably stinks.

Solutions? You could use an entity listener called on entity creation and then use a service dedicated only to properly compose your object(s), maybe something like a Factory. In this way, your entity stays lightweight, the lifecycle management is satisfied and the entity composing is responsibility only of your service.

Upvotes: 1

Related Questions