简体   繁体   中英

Doctrine one-to-many returning null

I'm trying to map a Milestones to a Project but when I try to reference the relation it's always returning null.

The database looks perfect, the targetEntity paths are correct and the scheme is validating by using

doctrine:scheme:validate

project.php

/**
 * @ORM\OneToMany(targetEntity="Planning\Readmodel\Project\Milestone\Milestone", mappedBy="project", cascade={"persist", "remove"})
 */
private $milestones;

milestone.php

/**
 * @ORM\ManyToOne(targetEntity="Planning\Readmodel\Project\Project", inversedBy="milestones", cascade={"persist", "remove"})
 * @ORM\JoinColumn(name="projectId", referencedColumnName="projectId")
 */
private $project;

But when I try to get the milestone I get null using:

$this->milestones;

Any idea what I might be doing wrong? Thank you.

Your owning entity definition ie Project looks fine to me but your inversed entity ie Milestone has a problem in JoinColumn annotation in JoinColumn annotation name relates to the column of your current entity which hold the relation to project entity but in referencedColumnName you have to provide the column of your parent entity that is primary key of project entity which should be referencedColumnName="id"

So your annotation for milestone entity should be like

/**
 * @ORM\ManyToOne(targetEntity="Planning\Readmodel\Project\Project", inversedBy="milestones", cascade={"persist", "remove"})
 * @ORM\JoinColumn(name="project_id", referencedColumnName="id")
 */
private $project;

According to the official docs 5.11. Mapping Defaults

The name of the join table defaults to a combination of the simple, unqualified class names of the participating classes, separated by an underscore character. The names of the join columns default to the simple, unqualified class name of the targeted class followed by “_id”. The referencedColumnName always defaults to “id”, just as in one-to-one or many-to-one mappings.

Make sure to update your database by running doctrine update command

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM