создать несколько записей в нескольких разных таблицах с помощью API Platform - PullRequest
0 голосов
/ 27 декабря 2018

Я использую API-платформу для Symfony REST API.Я ищу с одним маршрутом добавить несколько данных в нескольких разных таблицах, поэтому несколько объектов.Вот путь, по которому я хочу пойти:

/ api / order

<?php

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ApiResource()
 * @ORM\Entity(repositoryClass="App\Repository\OrderRepository")
 */
class Order
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

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

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

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

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

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\OrderHistory", mappedBy="orderId")
     */
    private $orderHistories;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Customer", inversedBy="orders")
     * @ORM\JoinColumn(nullable=false)
     */
    private $customer;

    /**
     * @ORM\Column(type="integer")
     */
    private $weightMerchant;

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

    /**
     * @ORM\Column(type="integer")
     */
    private $taxeOctroi;

    /**
     * @ORM\Column(type="integer")
     */
    private $taxeOctroiRegional;

    /**
     * @ORM\Column(type="integer")
     */
    private $taxeTva;

    /**
     * @ORM\Column(type="integer")
     */
    private $taxeOctroiMerchant;

    /**
     * @ORM\Column(type="integer")
     */
    private $taxeOctroiRegionalMerchant;

    /**
     * @ORM\Column(type="integer")
     */
    private $taxeTvaMerchant;

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

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

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\OrderDetail", mappedBy="orderId")
     */
    private $orderDetails;

    /**
     * Order constructor.
     */
    public function __construct()
    {
        $this->date_add = new \DateTime();
        $this->date_upd = new \DateTime();
        $this->orderHistories = new ArrayCollection();
        $this->orderDetails = new ArrayCollection();
    }

    /**
     * @return int|null
     */
    public function getId(): ?int
    {
        return $this->id;
    }

    /**
     * @return null|string
     */
    public function getOrigin(): ?string
    {
        return $this->origin;
    }

    /**
     * @param string $origin
     * @return Order
     */
    public function setOrigin(string $origin): self
    {
        $this->origin = $origin;

        return $this;
    }

    /**
     * @return null|string
     */
    public function getDestination(): ?string
    {
        return $this->destination;
    }

    /**
     * @param string $destination
     * @return Order
     */
    public function setDestination(string $destination): self
    {
        $this->destination = $destination;

        return $this;
    }

    /**
     * @return null|string
     */
    public function getIdTrackingMerchant(): ?string
    {
        return $this->idTrackingMerchant;
    }

    /**
     * @param string $idTrackingMerchant
     * @return Order
     */
    public function setIdTrackingMerchant(string $idTrackingMerchant): self
    {
        $this->idTrackingMerchant = $idTrackingMerchant;

        return $this;
    }

    /**
     * @return null|string
     */
    public function getIdTrackingA(): ?string
    {
        return $this->idTrackingA;
    }

    /**
     * @param string $idTrackingA
     * @return Order
     */
    public function setIdTrackingA(string $idTrackingA): self
    {
        $this->idTrackingA = $idTrackingA;

        return $this;
    }

    /**
     * @return Collection|OrderHistory[]
     */
    public function getOrderHistories(): Collection
    {
        return $this->orderHistories;
    }

    /**
     * @param OrderHistory $orderHistory
     * @return Order
     */
    public function addOrderHistory(OrderHistory $orderHistory): self
    {
        if (!$this->orderHistories->contains($orderHistory)) {
            $this->orderHistories[] = $orderHistory;
            $orderHistory->setOrderId($this);
        }

        return $this;
    }

    /**
     * @param OrderHistory $orderHistory
     * @return Order
     */
    public function removeOrderHistory(OrderHistory $orderHistory): self
    {
        if ($this->orderHistories->contains($orderHistory)) {
            $this->orderHistories->removeElement($orderHistory);
            // set the owning side to null (unless already changed)
            if ($orderHistory->getOrderId() === $this) {
                $orderHistory->setOrderId(null);
            }
        }

        return $this;
    }

    /**
     * @return Customer|null
     */
    public function getCustomer(): ?Customer
    {
        return $this->customer;
    }

    /**
     * @param Customer|null $customer
     * @return Order
     */
    public function setCustomer(?Customer $customer): self
    {
        $this->customer = $customer;

        return $this;
    }

    /**
     * @return int|null
     */
    public function getWeightMerchant(): ?int
    {
        return $this->weightMerchant;
    }

    /**
     * @param int $weightMerchant
     * @return Order
     */
    public function setWeightMerchant(int $weightMerchant): self
    {
        $this->weightMerchant = $weightMerchant;

        return $this;
    }

    /**
     * @return int|null
     */
    public function getWeightReal(): ?int
    {
        return $this->weightReal;
    }

    /**
     * @param int|null $weightReal
     * @return Order
     */
    public function setWeightReal(?int $weightReal): self
    {
        $this->weightReal = $weightReal;

        return $this;
    }

    /**
     * @return int|null
     */
    public function getTaxeTva(): ?int
    {
        return $this->taxeTva;
    }

    /**
     * @param int $taxeTva
     * @return Order
     */
    public function setTaxeTva(int $taxeTva): self
    {
        $this->taxeTva = $taxeTva;

        return $this;
    }

    /**
     * @return int|null
     */
    public function getTaxeOctroi(): ?int
    {
        return $this->taxeOctroi;
    }

    /**
     * @param int $taxeOctroi
     * @return Order
     */
    public function setTaxeOctroi(int $taxeOctroi): self
    {
        $this->taxeOctroi = $taxeOctroi;

        return $this;
    }

    /**
     * @return int|null
     */
    public function getTaxeOctroiRegional(): ?int
    {
        return $this->taxeOctroiRegional;
    }

    /**
     * @param int $taxeOctroiRegional
     * @return Order
     */
    public function setTaxeOctroiRegional(int $taxeOctroiRegional): self
    {
        $this->taxeOctroiRegional = $taxeOctroiRegional;

        return $this;
    }

    /**
     * @return int|null
     */
    public function getTaxeTvaMerchant(): ?int
    {
        return $this->taxeTvaMerchant;
    }

    /**
     * @param int $taxeTvaMerchant
     * @return Order
     */
    public function setTaxeTvaMerchant(int $taxeTvaMerchant): self
    {
        $this->taxeTvaMerchant = $taxeTvaMerchant;

        return $this;
    }

    /**
     * @return int|null
     */
    public function getTaxeOctroiMerchant(): ?int
    {
        return $this->taxeOctroiMerchant;
    }

    /**
     * @param int $taxeOctroiMerchant
     * @return Order
     */
    public function setTaxeOctroiMerchant(int $taxeOctroiMerchant): self
    {
        $this->taxeOctroiMerchant = $taxeOctroiMerchant;

        return $this;
    }

    /**
     * @return int|null
     */
    public function getTaxeOctroiRegionalMerchant(): ?int
    {
        return $this->taxeOctroiRegionalMerchant;
    }

    /**
     * @param int $taxeOctroiRegionalMerchant
     * @return Order
     */
    public function setTaxeOctroiRegionalMerchant(int $taxeOctroiRegionalMerchant): self
    {
        $this->taxeOctroiRegionalMerchant = $taxeOctroiRegionalMerchant;

        return $this;
    }

    /**
     * @return \DateTimeInterface|null
     */
    public function getDateAdd(): ?\DateTimeInterface
    {
        return $this->date_add;
    }

    /**
     * @return \DateTimeInterface|null
     */
    public function getDateUpd(): ?\DateTimeInterface
    {
        return $this->date_upd;
    }

    /**
     * @param \DateTimeInterface $date_upd
     * @return Order
     */
    public function setDateUpd(\DateTimeInterface $date_upd): self
    {
        $this->date_upd = $date_upd;

        return $this;
    }

    /**
     * @return Collection|OrderDetail[]
     */
    public function getOrderDetails(): Collection
    {
        return $this->orderDetails;
    }

    /**
     * @param OrderDetail $orderDetail
     * @return Order
     */
    public function addOrderDetail(OrderDetail $orderDetail): self
    {
        if (!$this->orderDetails->contains($orderDetail)) {
            $this->orderDetails[] = $orderDetail;
            $orderDetail->setOrderId($this);
        }

        return $this;
    }

    /**
     * @param OrderDetail $orderDetail
     * @return Order
     */
    public function removeOrderDetail(OrderDetail $orderDetail): self
    {
        if ($this->orderDetails->contains($orderDetail)) {
            $this->orderDetails->removeElement($orderDetail);
            // set the owning side to null (unless already changed)
            if ($orderDetail->getOrderId() === $this) {
                $orderDetail->setOrderId(null);
            }
        }

        return $this;
    }
}

эта сущность имеет отношение к сущности OrderDetail и OrderHistory, именно эти две сущности, которые я должен добавить данныек их столам.Как я могу сделать это с помощью API Platform?

Спасибо за вашу помощь.

error

1 Ответ

0 голосов
/ 28 декабря 2018

Чтобы сохранить внедренные сущности в одном запросе, необходимо использовать группы сериализатора и включить сохранение каскада.

Сначала примените группы сериализатора к не встроенным свойствам сущности заказа.

use Symfony\Component\Serializer\Annotation\Groups;

...

/**
 * @ORM\Id()
 * @ORM\GeneratedValue()
 * @ORM\Column(type="integer")
 * @Groups("order")
 */
 private $id;

Затем примените группы к встроенным свойствам и добавьте параметры каскада:

/**
 * @ORM\OneToMany(targetEntity="App\Entity\OrderDetail", mappedBy="orderId", cascade={"persist", "remove"})
 * @Groups("order:order_detail")
 */
 private $orderDetails;

Затем примените группы к свойствам встроенного объекта:

public class OrderDetail {

/**
 * ...
 * @Groups("order_detail")
 */
 private $id;

 ...

}

И добавьте их в контекст сериализации, если выне хотите, чтобы они были внедрены при извлечении данных, вы можете удалить группы из normalizationContext:

/**
 * @ApiResource(
 *  normalizationContext={"groups"={"order", "order:order_detail", "order_detail"}},
 *  denormalizationContext={"groups"={"order", "order:order_detail", "order_detail"}}
 *)
 * @ORM\Entity(repositoryClass="App\Repository\OrderRepository")
 */
class Order {  }

Теперь вы можете сохранить их с помощью одного запроса:

POST /orders
{
  ...
  orderDetails: [{ "myProperty": "myValue", ... }]
}

Другой альтернативой является использование подресурса , но сначала необходимо сохранить объект заказа.

...