【问题标题】:fetch ManyToMany data with symfony使用 symfony 获取 ManyToMany 数据
【发布时间】:2021-04-16 15:28:21
【问题描述】:

我有两个实体 Book 和 Author 在第三个表 (ManyToMany) book_author 中相关

作者表

| id | name | email | books_count|
|    |      |       |            |

书桌

| id | title | 
|    |       |   

book_author

| book_id | author_id | 
|         |           |  

图书实体

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiResource;
use App\Repository\BookRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Annotations;
/**
 * @ApiResource()
 * @ORM\Entity(repositoryClass=BookRepository::class)
 * 
 */
class Book
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     * 
     */
    private $id;

    /**
     * @ORM\Column(type="text")
     */
    private $title;

    /**
     * @ORM\ManyToMany(targetEntity=Author::class, inversedBy="books")
     * @ORM\JoinTable(name="book_author")
    * )
     */
    private $authors;

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

    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;
    }

    /**
     * @return Collection|Author[]
     */
    public function getAuthors(): Collection
    {
        return $this->authors;
    }

    public function addAuthor(Author $author): self
    {
        if (!$this->authors->contains($author)) {
            $this->authors[] = $author;
        }

        return $this;
    }

    public function removeAuthor(Author $author): self
    {
        $this->authors->removeElement($author);

        return $this;
    }
}

作者实体

<?php

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiResource;
use App\Repository\BookRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Annotations;
/**
 * @ApiResource()
 * @ORM\Entity(repositoryClass=BookRepository::class)
 * 
 */
class Book
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     * 
     */
    private $id;

    /**
     * @ORM\Column(type="text")
     */
    private $title;

    /**
     * @ORM\ManyToMany(targetEntity=Author::class, inversedBy="books")
     * @ORM\JoinTable(name="book_author")
    * )
     */
    private $authors;

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

    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;
    }

    /**
     * @return Collection|Author[]
     */
    public function getAuthors(): Collection
    {
        return $this->authors;
    }

    public function addAuthor(Author $author): self
    {
        if (!$this->authors->contains($author)) {
            $this->authors[] = $author;
        }

        return $this;
    }

    public function removeAuthor(Author $author): self
    {
        $this->authors->removeElement($author);

        return $this;
    }
}

我需要得到:book.id、book.title、author.id、author.name、author.bookscount,因为我必须对它们进行序列化才能获得这种 JSON 格式:

    {
  "id": 1,
  "title": "Test title",
  "authors":  [
    {
      "id": 1,
      "name": "Author name",
      "booksCount": 1
    },
    {
      "id": 2,
      "name": "Another author name",
      "booksCount": 3
    }
  ]
}

所以,在我的书控制器中,我这样做:

/**
 * @Route("/api/book/{id}", name="api_book_get", methods={"GET"})
 */
public function getBookById(BookRepository $bookRepository, $id, SerializerInterface $serializer)
{

    return $this->json($bookRepository->find($id), 200, []);
}

但我得到的 JSON 是:

{
    "id": 1,
    "title": "Test title",
    "authors": [
        "/api/authors/2"
    ]
}

为什么在“作者”中我得到“/api/authors/2”而不是作者表的值?

【问题讨论】:

    标签: json api symfony request doctrine


    【解决方案1】:

    这是 API 平台默认规范化。

    您可以在实体中定义规范化上下文。

    // src/Entity/Book.php
    // ...
    use Symfony\Component\Serializer\Annotation\Groups;
    
    /**
     * @ApiResource(normalizationContext={"groups"={"book"}})
     */
    class Book
    {
        /**
         * @Groups({"book"})
         */
        public $title;
    
        /**
         * @Groups({"book"})
         */
        public $authors;
    
        // ...
    
    }
    
    // src/Entity/Author.php
    // ...
    use Symfony\Component\Serializer\Annotation\Groups;
    
    /**
     * @ApiResource
     */
    class Author
    {
        /**
         * ...
         * @Groups("book")
         */
        public $name;
    
        // ...
    }
    

    Read more

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-04
      • 2019-07-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-20
      • 2019-10-31
      相关资源
      最近更新 更多