In Symfony 5, I've created 2 entities related with a ManyToOne relation : Project
is the parent, Serie
is the child.
Project
entity :
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass="App\Repository\SerieRepository")
*/
class Serie
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=100)
*/
private $name;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Project", inversedBy="series")
* @ORM\JoinColumn(nullable=false)
*/
private $project;
[...]
}
Serie
entity :
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass="App\Repository\ProjectRepository")
*/
class Project
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=100)
*/
private $name;
/**
* @ORM\OneToMany(targetEntity="App\Entity\Serie", 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...).