Symfony Accessing to parent entity inside entity class

In Symfony 5, I’ve created 2 entities related with a ManyToOne relation : Project is the parent, Serie is the child.

Project entity :

namespace AppEntity;

use DoctrineCommonCollectionsArrayCollection;
use DoctrineCommonCollectionsCollection;
use DoctrineORMMapping as ORM;

/**
 * @ORMEntity(repositoryClass="AppRepositorySerieRepository")
 */
class Serie
{
    /**
     * @ORMId()
     * @ORMGeneratedValue()
     * @ORMColumn(type="integer")
     */
    private $id;

    /**
     * @ORMColumn(type="string", length=100)
     */
    private $name;

    /**
     * @ORMManyToOne(targetEntity="AppEntityProject", inversedBy="series")
     * @ORMJoinColumn(nullable=false)
     */
    private $project;

    [...]
}

Serie entity :

namespace AppEntity;


use DoctrineCommonCollectionsArrayCollection;
use DoctrineCommonCollectionsCollection;
use DoctrineORMMapping as ORM;

/**
 * @ORMEntity(repositoryClass="AppRepositoryProjectRepository")
 */
class Project
{
    /**
     * @ORMId()
     * @ORMGeneratedValue()
     * @ORMColumn(type="integer")
     */
    private $id;

    /**
     * @ORMColumn(type="string", length=100)
     */
    private $name;


    /**
     * @ORMOneToMany(targetEntity="AppEntitySerie", mappedBy="Project", orphanRemoval=true)
     */
    private $series;

    [...]
}

I didn’t write down here, but you also have all the getter and setter for each class.

I need to access to the Project entity in the Serie entity. For example : accessing to the name property of Project entity by adding a getProjectName method in Serie class.

    public function getProjectName()
    {
        return $this->project->getName();
    }

But this is not working as the Project entity is not loaded (only the id). How can I get this value, without adding a repository in the entity class or passing any argument to the getProjectName method ? (maybe a Doctrine annotation…).

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *