[英]Symfony3 One-To-Many relation not working
I have entity Project
and Files
. 我有实体
Project
和Files
。 One project can have multiple files and one file belongs only to one project. 一个项目可以有多个文件,而一个文件仅属于一个项目。 Here is how my relationship is done
这是我的关系完成的方式
In Files
Entity 在
Files
实体中
/**
* @ORM\ManyToOne(targetEntity="AppBundle\Entity\Project", inversedBy="files")
* @ORM\JoinColumn(name="project_id", referencedColumnName="id")
*/
private $project;
In Project
Entity: 在
Project
实体中:
/**
* @var ArrayCollection
* @ORM\OneToMany(targetEntity="AppBundle\Entity\Files", mappedBy="project")
*/
private $files;
Here is how a new File is created after being uploaded 这是上传后创建新文件的方式
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();
}
This function is called in ProjectController
after flushing the project (which gives it ID which then I can use to create my file). 刷新项目后,将在
ProjectController
中调用此函数(这将为其提供ID,然后我可以使用该ID来创建我的文件)。 Here is the code 这是代码
$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);
}
After everything is set and done I have a project and files. 一切设置完成后,我有了一个项目和文件。 In files table I see that
project_id
is with the id of the created project. 在文件表中,我看到
project_id
与创建的项目的ID。 Then I try to get from the project all files using files
property. 然后,我尝试使用
files
属性从项目中获取所有文件。 In my controller I have dump(project->getFiles());
在我的控制器中,我有
dump(project->getFiles());
which so far returns this 到目前为止返回
Even though I have in my database files which have the id of the project my files
is not filled with files. 即使我的数据库文件中包含项目ID,我的
files
也没有填充文件。 I suppose my mistake is in the annotations, but I have no idea how to fix this. 我想我的错误在于注释中,但我不知道如何解决。
Relations are (by default) loaded lazy in Doctrine. 关系(默认情况下)在Doctrine中是延迟加载的。 Meaning: it isn't fetched from the database until you access it.
含义:直到您访问它,才从数据库中获取它。
Try to foreach through the getFiles. 尝试遍历getFiles。 You will see you can access them.
您将看到可以访问它们。
What is the difference between fetch="EAGER" and fetch="LAZY" in doctrine including further links in that Top Answer to Doctrine itself to explain it further. 在学说中, fetch =“ EAGER”和fetch =“ LAZY”之间有什么区别,包括该最佳答案本身中进一步的链接以进一步解释该学说。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.