方法PUT OneToMany关系? (api平台)

时间:2019-01-18 19:17:27

标签: symfony api-platform.com

精算师实体

<?php

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiResource;

/**
 * @ApiResource(
 *     normalizationContext={"groups"={"get"}, "enable_max_depth"=true},
 *     denormalizationContext={"groups"={"write"}}
 * )
 * @ORM\Entity(repositoryClass="App\Repository\ActualiteRepository")
 */
class Actualite
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @var string titre actualite
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank
     * @Groups({"get", "write"})
     */
    private $titre;

    /**
     * @var text contenu actualite
     * @ORM\Column(type="text")
     * @Assert\NotBlank
     * @Groups({"write", "get"})
     */
    private $contenu;

    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Comment", mappedBy="actualite", cascade={"all"})
     * @Groups({"get"})
     */
    private $comments;


    public function __construct()
    {
        $this->comments = 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;
    }

    /**
     * @return Collection|Comment[]
     */
    public function getComments(): Collection
    {
        return $this->comments;
    }

    public function addComment(Comment $comment): self
    {
        if (!$this->comments->contains($comment)) {
            $this->comments[] = $comment;
            $comment->setActualite($this);
        }

        return $this;
    }

    public function removeComment(Comment $comment): self
    {
        if ($this->comments->contains($comment)) {
            $this->comments->removeElement($comment);
            // set the owning side to null (unless already changed)
            if ($comment->getActualite() === $this) {
                $comment->setActualite(null);
            }
        }

        return $this;
    }

    public function getContenu(): ?string
    {
        return $this->contenu;
    }

    public function setContenu(string $contenu): self
    {
        $this->contenu = $contenu;

        return $this;
    }


}

评论实体:

<?php

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiResource;

/**
 * @ApiResource(
 *     normalizationContext={"groups"={"get"}, "enable_max_depth"=true},
 * )
 * @ORM\Entity(repositoryClass="App\Repository\CommentRepository")
 */
class Comment
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Actualite", inversedBy="comments")
     * @ORM\JoinColumn(name="actualite_id", referencedColumnName="id")
     * @Assert\NotBlank
     * @Groups({"get"})
     * @MaxDepth(1)
     */
    private $actualite;

    /**
     * @var string email
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank
     */
    private $email;


    /**
     * @var text commentaire
     * @ORM\Column(type="text")
     * @Assert\NotBlank
     * @Groups({"get"})
     */
    private $message;


    public function __construct()
    {
        $this->ajouter = new \Datetime();
    }

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

    public function getActualite(): ?Actualite
    {
        return $this->actualite;
    }

    public function setActualite(?Actualite $actualite): self
    {
        $this->actualite = $actualite;

        return $this;
    }

    public function getEmail(): ?string
    {
        return $this->email;
    }

    public function setEmail(string $email): self
    {
        $this->email = $email;

        return $this;
    }

    public function getMessage(): ?string
    {
        return $this->message;
    }

    public function setMessage(string $message): self
    {
        $this->message = $message;

        return $this;
    }
}

在表中插入一些数据后,一切运行正常:

在表Actualite

+----+---------+---------+ 
| id | titre   | contenu |
+----+---------+---------+ 
| 1  | titre1  | lorem 1 |
| 2  | titre2  | lorem2  |
| 3  | titre3  | lorem3 |
+----+---------+---------+

表注释

+----+--------------+---------+-----------+
| id | actualite_id | email   | message   |
+----+--------------+---------+-----------+ 
| 1  |       1      | e@e.com | someText  |
| 2  |       2      | b@b.com | someText1 |
| 3  |       2      | a@a.com | text      |
| 4  |       3      | q@a.com | text2     |
+----+--------------+---------+-----------+

我想更改Actualite表中的iten的ID(id = 2),我还必须更改相关表中的actualite_id:例如==>

在表Actualite

+----+---------+---------+ 
| id | titre   | contenu |
+----+---------+---------+ 
| 1  | titre1  | lorem 1 |
| 4  | titre2  | lorem2  |
| 3  | titre3  | lorem3  |
+----+---------+---------+

表注释

+----+--------------+---------+-----------+
| id | actualite_id | email   | message   |
+----+--------------+---------+-----------+ 
| 1  |       1      | e@e.com | someText  |
| 2  |       4      | b@b.com | someText1 |
| 3  |       4      | a@a.com | text      |
| 4  |       3      | q@a.com | text2     |
+----+--------------+---------+-----------+

我尝试使用 Api平台方法执行此操作,但该方法无效:

Json请求: 网址:http://127.0.0.1:8000/api/actualites/2

{
  "id": 4
} 

什么都没有改变!

我也试图通过使用Costum控制器来执行此操作:

// scr/Controller/CustomController.php
<?php
namespace App\Controller;

use App\Entity\Actualite;
use App\Entity\Comment;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

class CustomController extends AbstractController
{
    /**
     *
     * @Route("/cid")
     */

    public function cidAction()
    {

        $em = $this->getDoctrine()->getManager();
        $actualite = $this->getDoctrine()
            ->getRepository(Actualite::class)
            ->cid('2', '4');
        return new Response('ok', Response::HTTP_CREATED);

    }
}

<?php
/// src/RepositoryActualiteRepository.php

namespace App\Repository;

use App\Entity\Actualite;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Symfony\Bridge\Doctrine\RegistryInterface;

/**
 * @method Actualite|null find($id, $lockMode = null, $lockVersion = null)
 * @method Actualite|null findOneBy(array $criteria, array $orderBy = null)
 * @method Actualite[]    findAll()
 * @method Actualite[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class ActualiteRepository extends ServiceEntityRepository
{
    public function __construct(RegistryInterface $registry)
    {
        parent::__construct($registry, Actualite::class);
    }
    /**
     * @return Actualite[] Returns an array of Actualite objects
     */
    public function cid($id, $value)
    {
      $qb = $this->createQueryBuilder('a')
        ->update()
        ->set('a.id', $value)
        ->where('a.id = :val')
        ->setParameter('val', $id); 

        return $qb->getQuery()->getResult();
    }
}

我收到错误冲突:

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`api`.`comment`, CONSTRAINT `FK_9474526CA2843073` FOREIGN KEY (`actualite_id`) REFERENCES `actualite` (`id`))

如何更改Actualite实体中的项目ID,并更改相关实体中的Actualite_id?

如何执行此操作?

0 个答案:

没有答案