因此,我正在尝试创建一种将Recipies
插入MySQL数据库的方法。
recipe
(Recette)具有很多Ingredients
的我项目的架构。
[Recette
有一个Title
(titre),Subtitle
(Soustitre)和Ingredients
,必须在“ POST”请求中插入。我将向您显示我的代码,在Postman和我得到的结果。
此外,我的相同代码具有无法正常运行的更新功能,并且始终是构成问题。
这是我的控制器:
namespace App\Controller;
use App\Entity\Ingredients;
use App\Entity\Recettes;
use Doctrine\ORM\EntityManagerInterface;
use http\Env\Response;
use Psr\Container\ContainerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use App\Repository\RecettesRepository;
use Symfony\Component\Serializer\Exception\NotEncodableValueException;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Validator\Validator\ValidatorInterface;
class ApiRecetteController extends AbstractController
{
/**
* @Route("/api/recette", name="api_recette_index", methods={"GET"})
*/
public function index(RecettesRepository $recettesRepository)
{
return $this->json($recettesRepository->findAll(), 200, [], ['groups' => 'recette:read']);
}
/**
* @Route("/api/recette", name="api_recette_addRecettes", methods={"POST"})
*/
public function addRecettes(Request $request, SerializerInterface $serializer, EntityManagerInterface
$entityManager)
{
$jsonRecu = $request->getContent();
try {
$recette = $serializer->deserialize($jsonRecu, Recettes::class,"json");
$entityManager->persist($recette);
$entityManager->flush();
return $this->json($recette,201);
}
catch (NotEncodableValueException $e){
return $this->json([
'status'=>400,
'message' =>$e->getMessage()
],400);
}
}
/**
* @Route("/api/recette/Update/{id}", name="api_recette_updateRecettes", methods={"PUT"})
*/
public function UpdateRecettes($id, RecettesRepository $recettesRepository, Request $request,
EntityManagerInterface $entityManager)
{
$entityManger = $this->getDoctrine()->getManager();
$recettes = $entityManger->getRepository(Recettes::class)->find($id);
$data = json_decode($request->getContent(), true);
if (!$recettes) {
throw $this->createNotFoundException(
'Aucune recette trouvé pour id' . $id
);
}
empty($data['Titre']) ? true : $recettes->setTitre($data['Titre']);
empty($data['Soustitre']) ? true : $recettes->setSoustitre($data['Soustitre']);
$entityManager->persist($recettes);
$entityManger->flush();
return $this->json($recettes,204, [], ['groups' => 'recette:read']);
}
/**
* @Route("/api/recette/{id}", name="api_recette_DeleteRecettes", methods={"DELETE"})
*/
public function DeleteRecettes($id, EntityManagerInterface $entityManager, Request $request)
{
$recettes = $entityManager->getRepository(Recettes::class)->find($id);
$entityManager->remove($recettes);
$entityManager->flush();
return $this->json($recettes,202, [], ['groups' => 'recette:read']);
}
}
和我的两个实体
<?PHP
namespace App\Entity;
use App\Repository\IngredientsRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;
/**
* @ORM\Entity(repositoryClass="App\Repository\IngredientsRepository",
repositoryClass=IngredientsRepository::class)
*/
class Ingredients
{
/**
* @ORM\Id()
* @ORM\GeneratedValue(strategy="AUTO")
* @ORM\Column(type="integer")
* @Groups("recette:read")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
* @Groups("recette:read")
*/
private $name;
/**
* @ORM\ManyToOne(targetEntity=Recettes::class, inversedBy="ingredients")
* @ORM\JoinColumn(nullable=false)
*/
private $recettes;
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 getRecettes(): ?Recettes
{
return $this->recettes;
}
public function setRecettes(?Recettes $recettes): self
{
$this->recettes = $recettes;
return $this;
}
public function __toString(): ?string
{
return $this->getName();
}
}
和食谱
<?PHP
namespace App\Entity;
use App\Repository\RecettesRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;
/**
* @ORM\Entity(repositoryClass=RecettesRepository::class)
*/
class Recettes
{
/**
* @ORM\Id()
* @ORM\GeneratedValue(strategy="AUTO")
* @ORM\Column(type="integer")
* @Groups("recette:read")
*/
private $id;
/**
* @ORM\Column(type="string", length=255)
* @Groups("recette:read")
*/
private $Titre;
/**
* @ORM\Column(type="string", length=255, nullable=true)
* @Groups("recette:read")
*/
private $Soustitre;
/**
* @ORM\OneToMany(targetEntity=Ingredients::class, mappedBy="recettes")
*/
private $ingredients;
public function __construct()
{
$this->ingredients = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getTitre(): ?string
{
return $this->Titre;
}
public function setTitre(string $Titre): self
{
$this->Titre = $Titre;
return $this;
}
public function getSoustitre(): ?string
{
return $this->Soustitre;
}
public function setSoustitre(?string $Soustitre): self
{
$this->Soustitre = $Soustitre;
return $this;
}
/**
* @return Collection|Ingredients[]
*/
public function getingredients(): Collection
{
return $this->ingredients;
}
public function addingredients(Ingredients $ingredients): self
{
if (!$this->ingredients->contains($ingredients)) {
$this->ingredients[] = $ingredients;
$ingredients->setRecettes($this);
}
return $this;
}
public function removeingredients(Ingredients $ingredients): self
{
if ($this->ingredients->contains($ingredients)) {
$this->ingredients->removeElement($ingredients);
// set the owning side to null (unless already changed)
if ($ingredients->getRecettes() === $this) {
$ingredients->setRecettes(null);
}
}
return $this;
}
}
我的请求json
我的状态为201正常,但插入的配料为空
要插入相关实体,需要为您的关系设置cascade={"persist"}
,即:
/**
* @ORM\OneToMany(targetEntity=Ingredients::class, mappedBy="recettes", cascade={"persist"})
*/
private $ingredients;
否则,您将需要先保留配方,在保留它们之前获取ID并将其设置在您的配料上。