【问题标题】:Symfony 4 how to upload multiple images in relation oneToMany?Symfony 4如何上传有关oneToMany的多个图像?
【发布时间】:2019-05-27 11:30:04
【问题描述】:

我来找你是因为我有一点麻烦我挡住了

我希望能够为一篇文章上传几张图片, 但我无法通过我正在阻止我不知道该怎么做

我分享一下我的代码,如果你能帮助我或者你有一些可以帮助我的教程,因为我看起来但有些教程不是很明确

在我的控制器中:

public function addArticle(Request $request): Response
{
    $article = new Article();
    $form = $this->createForm(ArticleType::class, $article);
    $form->handleRequest($request);

    if($form->isSubmitted() && $form->isValid()) {

        $file = $article->getImages();

        $fileName = $this->generateUniqueFileName().'.'.$file->guessExtension();

        try {
            $file->move(
                $this->getParameter('images_directory'),
                $fileName
            );
        } catch (FileException $e) {
            // ... handle exception if something happens during file upload
        }

        $em = $this->getDoctrine()->getManager();
        $em->persist($article);
        $em->flush();
    }

    return $this->render('backOffice/home/add-article.html.twig', [
        'form' => $form->createView()
    ]);
}

我的实体:

class Article
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank()
     * @Assert\Length(
     *      min = 5,
     *      max = 255,
     *      minMessage = "Votre titre doit contenir au minimum {{ limit }} caractères",
     *      maxMessage = "Votre titre doit contenir au maximum {{ limit }} caractères")
     */
    private $title;

    /**
     * @ORM\Column(type="text")
     * @Assert\NotBlank()
     * @Assert\Length(
     *     min="20",
     *     minMessage="Votre description doit contenir au minimum {{ limit }} caractères"
     * )
     */
    private $description;

    /**
     * @ORM\Column(type="datetime")
     */
    private $createdAt;

    /**
     * @ORM\Column(type="datetime", nullable=true)
     */
    private $updatedAt;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Image", mappedBy="article")
     * @Assert\NotBlank()
     * @Assert\File(
     *     mimeTypes={"image/jpeg", "image/png", "image/gif"},
     *     mimeTypesMessage = "Please upload a valid Image"
     *     )
     */
    private $images;

    /**
     * Article constructor.
     * @throws \Exception
     */
    public function __construct()
    {
        $this->images = new ArrayCollection();
        $this->createdAt = new \DateTime('now', new \DateTimeZone('Europe/Paris'));
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getTitle(): ?string
    {
        return $this->title;
    }

    public function setTitle(string $title): self
    {
        $this->title = $title;

        return $this;
    }

    public function getDescription(): ?string
    {
        return $this->description;
    }

    public function setDescription(string $description): self
    {
        $this->description = $description;

        return $this;
    }

    public function getCreatedAt(): ?\DateTimeInterface
    {
        return $this->createdAt;
    }

    public function setCreatedAt(\DateTimeInterface $createdAt): self
    {
        $this->createdAt = $createdAt;

        return $this;
    }

    public function getUpdatedAt(): ?\DateTimeInterface
    {
        return $this->updatedAt;
    }

    public function setUpdatedAt(?\DateTimeInterface $updatedAt): self
    {
        $this->updatedAt = $updatedAt;

        return $this;
    }

    /**
     * @return Collection|Image[]
     */
    public function getImages(): Collection
    {
        return $this->images;
    }

    public function addImage(Image $image): self
    {
        if (!$this->images->contains($image)) {
            $this->images[] = $image;
            $image->setArticle($this);
        }

        return $this;
    }

    public function removeImage(Image $image): self
    {
        if ($this->images->contains($image)) {
            $this->images->removeElement($image);
            // set the owning side to null (unless already changed)
            if ($image->getArticle() === $this) {
                $image->setArticle(null);
            }
        }

        return $this;
    }

}

在我的实体图片中:

class Image
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $name;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Article", inversedBy="images")
     * @ORM\JoinColumn(nullable=false)
     */
    private $article;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }

    public function getArticle(): ?Article
    {
        return $this->article;
    }

    public function setArticle(?Article $article): self
    {
        $this->article = $article;

        return $this;
    }

}

感谢您的帮助

【问题讨论】:

    标签: php symfony file-upload


    【解决方案1】:

    图像和文章是一对多的关系,但您的代码将其视为一对一的关系。 有两种方法可以解决这个问题: 1-

        $files = $article->getImages();
        foreach ($files as $file) {
            $fileName = $this->generateUniqueFileName().'.'.$file->guessExtension();
    
              try {
                    $file->move(
                      $this->getParameter('images_directory'),
                      $fileName
                );
              } catch (FileException $e) {
            // ... handle exception if something happens during file upload
              }
        }
    

    2- 在您的图像实体中使用生命周期回调在 PreUpdate 和 PrePersist 事件中将您的图像上传到服务器

    【讨论】:

    • 我有这个错误:>你能帮我吗?
    • 你用了什么方法?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-11
    • 2019-01-06
    • 1970-01-01
    • 2019-02-18
    • 1970-01-01
    相关资源
    最近更新 更多