bratniak
bratniak

Reputation: 1

Duplicate entry '1' for key Symfony

when I'm trying create new entry I've got that informations(symfony):

An exception occurred while executing a query: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1' for key 'UNIQ_ED896F46AF89CCED'
This error I have when in db is something actually, so first entries are doing good.
I'm using mariadb. Symfony version is 6+.
Controller Order:

<?php

namespace App\Controller;

use App\Entity\OrderDetail;
use App\Entity\Product;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\HttpFoundation\Request;
use App\Entity\Order;

class OrderController extends AbstractController
{
    #[Route('/order', name: 'create_order', methods: ['POST'])]
    public function createOrder(Request $request, EntityManagerInterface $em): JsonResponse
    {
        $data = json_decode($request->getContent(), true);

        if (empty($data))
            return new JsonResponse(['error' => 'Error Processing Request'], 404);

        $order = new Order();
        $order->setCreateat(new \DateTime());

        $total = 0;
        foreach ($data as $item) {
            $product = $em->getRepository(Product::class)->find($item['id']);

            if (!$product) {
                return new JsonResponse(['error' => 'Product not found'], 404);
            }

            $orderDetail = new OrderDetail();
            $orderDetail->setProductid($product);
            $orderDetail->setQuantity($item['quantity']);
            $orderDetail->setPrice($product->getPrice() * $item['quantity']);
            $orderDetail->setOrderid($order);

            $total += $orderDetail->getPrice();

            $order->addOrderDetail($orderDetail);
            $em->persist($orderDetail);
        }
        $order->setTotal($total);
        $order->setUpdateat(new \DateTime());
        $order->setStatus(Order::STATUS_NEW);
        $em->persist($order);
        $em->flush();

        return new JsonResponse($order, 200);
    }
}

Order entity:

<?php

namespace App\Entity;

use App\Repository\OrderRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity(repositoryClass: OrderRepository::class)]
#[ORM\Table(name: '`order`')]
class Order
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    private ?int $id = null;

    #[ORM\Column(type: Types::DECIMAL, precision: 10, scale: 0)]
    private ?string $total = null;

    #[ORM\Column(type: Types::DATETIME_MUTABLE)]
    private ?\DateTimeInterface $createat = null;

    #[ORM\Column(type: Types::DATETIME_MUTABLE)]
    private ?\DateTimeInterface $updateat = null;

    #[ORM\Column]
    private ?int $status = null;

    /**
     * @var Collection<int, OrderDetail>
     */
    #[ORM\OneToMany(targetEntity: OrderDetail::class, mappedBy: 'orderid')]
    private Collection $productid;

    /**
     * @var Collection<int, OrderDetail>
     */
    #[ORM\OneToMany(targetEntity: OrderDetail::class, mappedBy: 'orderid')]
    private Collection $orderDetails;

    public const STATUS_NEW = 0;

    public function __construct()
    {
        $this->productid = new ArrayCollection();
        $this->orderDetails = new ArrayCollection();
    }

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

    public function getTotal(): ?string
    {
        return $this->total;
    }

    public function setTotal(string $total): static
    {
        $this->total = $total;

        return $this;
    }

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

    public function setCreateat(\DateTimeInterface $createat): static
    {
        $this->createat = $createat;

        return $this;
    }

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

    public function setUpdateat(\DateTimeInterface $updateat): static
    {
        $this->updateat = $updateat;

        return $this;
    }

    public function getStatus(): ?int
    {
        return $this->status;
    }

    public function setStatus(int $status): static
    {
        $this->status = $status;

        return $this;
    }

    /**
     * @return Collection<int, OrderDetail>
     */
    public function getProductid(): Collection
    {
        return $this->productid;
    }

    public function addProductid(OrderDetail $productid): static
    {
        if (!$this->productid->contains($productid)) {
            $this->productid->add($productid);
            $productid->setOrderid($this);
        }

        return $this;
    }

    public function removeProductid(OrderDetail $productid): static
    {
        if ($this->productid->removeElement($productid)) {
            // set the owning side to null (unless already changed)
            if ($productid->getOrderid() === $this) {
                $productid->setOrderid(null);
            }
        }

        return $this;
    }

    /**
     * @return Collection<int, OrderDetail>
     */
    public function getOrderDetails(): Collection
    {
        return $this->orderDetails;
    }

    public function addOrderDetail(OrderDetail $orderDetail): static
    {
        if (!$this->orderDetails->contains($orderDetail)) {
            $this->orderDetails->add($orderDetail);
            $orderDetail->setOrderid($this);
        }

        return $this;
    }

    public function removeOrderDetail(OrderDetail $orderDetail): static
    {
        if ($this->orderDetails->removeElement($orderDetail)) {
            // set the owning side to null (unless already changed)
            if ($orderDetail->getOrderid() === $this) {
                $orderDetail->setOrderid(null);
            }
        }

        return $this;
    }
}

OrderDetail entity:

<?php

namespace App\Entity;

use App\Repository\OrderDetailRepository;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity(repositoryClass: OrderDetailRepository::class)]
class OrderDetail
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    private ?int $id = null;

    #[ORM\ManyToOne(inversedBy: 'orderDetails')]
    private ?Order $orderid = null;

    #[ORM\OneToOne(cascade: ['persist', 'remove'])]
    private ?Product $productid = null;

    #[ORM\Column]
    private ?int $quantity = null;

    #[ORM\Column(type: Types::DECIMAL, precision: 10, scale: 0)]
    private ?string $price = null;

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

    public function getOrderid(): ?Order
    {
        return $this->orderid;
    }

    public function setOrderid(?Order $orderid): static
    {
        $this->orderid = $orderid;

        return $this;
    }

    public function getProductid(): ?Product
    {
        return $this->productid;
    }

    public function setProductid(?Product $productid): static
    {
        $this->productid = $productid;

        return $this;
    }

    public function getQuantity(): ?int
    {
        return $this->quantity;
    }

    public function setQuantity(int $quantity): static
    {
        $this->quantity = $quantity;

        return $this;
    }

    public function getPrice(): ?string
    {
        return $this->price;
    }

    public function setPrice(string $price): static
    {
        $this->price = $price;

        return $this;
    }
}

Guys any suggest? May I can't see something? Maybe this relation is problem.

Upvotes: 0

Views: 55

Answers (0)

Related Questions