多文件上传symfony 4

multiple file upload symfony 4

我试图在数据库中上传多张图片。但我的代码只上传最后一个选择。这是代码:

/**
     * @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()
        ]);
    }

如您所见,我正在从 class 实体调用对象。在这种情况下,文件上传器的形式接受多个文件或图像。

你的问题出在你的循环中。您正在使用相同的 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