我正在尝试上传数据库中的多个图像。 但我的代码只上传最后一个选定的。 这是代码:
/**
* @Route("/property/add-media/{id}", name="addPhotoProperty")
* @Method({"GET", "POST"})
*/
public function addPhotoToProperty(Request $request, $id){
$property = $this->getDoctrine()->getRepository(Property::class)->find($id);
$media = new Media();
$mediaForm = $this->createFormBuilder($media)
->add('pathtofile', FileType::class, array(
'mapped' => false,
'multiple' => true,
))
->add('isvideo', ChoiceType::class, [
'choices' => [
'Video' => '1',
'Photo' => '0'
],
'multiple' => false,
'expanded' => true
])
->add('upload', SubmitType::class)
->getForm();
$media->setProperty($property);
$mediaForm->handleRequest($request);
if ($mediaForm->isSubmitted() && $mediaForm->isValid()){
$files = $mediaForm->get('pathtofile')->getData();
//dd($files);
foreach ($files as $file)
{
$filename = md5(uniqid()).'.'.$file->guessExtension();
$file->move($this->getParameter('uploads'), $filename);
$media->setPathToFile($filename);
//dd($media);
$em = $this->getDoctrine()->getManager();
$em->persist($media);
$em->flush();
}
}
return $this->render('Property/addPhotoProperty.html.twig', [
'media' => $mediaForm->createView()
]);
}
如您所见,我正在从类实体调用对象。 在这种情况下,文件上传器的形式接受多个文件或图像。
你的问题出在你的循环中。您使用的是同一个Media
实体,并且只更改PathToFile
属性。首先$em->flush();
您正在创建一个新条目,但由于这是同一个实体(又名不是新实体),因此 Doctrine 正在进行更新。
foreach ($files as $file)
{
$filename = md5(uniqid()).'.'.$file->guessExtension();
$file->move($this->getParameter('uploads'), $filename);
$media->setPathToFile($filename); // Same entity, that is being updated
$em = $this->getDoctrine()->getManager();
$em->persist($media);
$em->flush();
}
我建议你在循环中创建一个新的。在示例中:
$em = $this->getDoctrine()->getManager(); // You don't need to slow down your code and request the same entity manager on each iteration
foreach ($files as $file)
{
$filename = md5(uniqid()).'.'.$file->guessExtension();
$file->move($this->getParameter('uploads'), $filename);
$NewMedia = new Media(); // new entity, that is being created
$NewMedia->setProperty($property);
$NewMedia->setPathToFile($filename);
$em->persist($NewMedia);
}
$em->flush(); //Flush outside of the loop, Doctrine will perform all queries