Symfony3 一对多关系不起作用

Symfony3 One-To-Many relation not working

我有实体 ProjectFiles。一个项目可以有多个文件,一个文件只属于一个项目。这是我的关系是如何完成的

Files 实体中

    /**
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Project", inversedBy="files")
     * @ORM\JoinColumn(name="project_id", referencedColumnName="id")
     */
    private $project;

Project 实体中:

    /**
     * @var ArrayCollection
     * @ORM\OneToMany(targetEntity="AppBundle\Entity\Files", mappedBy="project")
     */
    private $files;

这是上传后创建新文件的方式

public function createFile($fileName,$project,User $user){
        $file = new Files();
        $file->setFilePath($this->targetDirectory."/".$fileName);
        $file->setFromUser($user->getType());
        $file->setProject($project);
        $file->setDate(new \DateTime());
        dump($file);
        $this->entityManager->persist($file);
        $this->entityManager->flush();
    }

此函数在刷新项目后在 ProjectController 中调用(它为其提供 ID,然后我可以使用它来创建我的文件)。这是代码

$projectService->createProject($project, $user, $isWithoutTerm, self::NO_TERM_DEFAULT_VALUE);
$filesService = $this->get('app.service.files_service');
foreach ($managerFiles as $managerFile) {
   $fileName = $filesService->uploadFileAndReturnName($managerFile,$this->getParameter('files_directory'));
   $filesService->createFile($fileName, $project, $user);

 }

一切设置完成后,我就有了一个项目和文件。在文件 table 中,我看到 project_id 是创建项目的 ID。然后我尝试使用 files 属性 从项目中获取所有文件。在我的控制器中,我有 dump(project->getFiles()); 到目前为止 returns 这个

即使我的数据库文件中有项目 ID,但我的 files 中没有文件。我想我的错误在注释中,但我不知道如何解决这个问题。

关系(默认情况下)在 Doctrine 中延迟加载。含义:在您访问它之前,它不会从数据库中获取。

尝试通过 getFiles foreach。您会看到您可以访问它们。

What is the difference between fetch="EAGER" and fetch="LAZY" in doctrine 包括进一步解释教义本身的最佳答案中的链接。