首页 > 解决方案 > 请求返回 IRI 而不是嵌套关系中的对象

问题描述

假设我有两个实体:书籍和作者,它们的设置如下:

作者.php

/**
* @ApiResource(attributes={
*     "normalization_context"={"groups"={"author"}, "enable_max_depth"=true},
*     "denormalization_context"={"groups"={"author"}, "enable_max_depth"=true}
* })
* @ORM\Entity(repositoryClass="App\Repository\AuthorRepository")
*/
class Author
{
...
/**
    * @ORM\OneToMany(targetEntity="App\Entity\Book", mappedBy="author", orphanRemoval=true)
    * @Groups({"author", "book"})
    * @MaxDepth(3)
    */
    private $books;

书本.php

/**
* @ApiResource(attributes={
*     "normalization_context"={"groups"={"book"}, "enable_max_depth"=true},
*     "denormalization_context"={"groups"={"book"}, "enable_max_depth"=true}
* })
* @ORM\Entity(repositoryClass="App\Repository\BookRepository")
*/
class Book
{
...
/**
    * @ORM\ManyToOne(targetEntity="App\Entity\Author", inversedBy="books")
    * @ORM\JoinColumn(nullable=false)
    * @Groups({"book", "author"})
    * @MaxDepth(3)
    */
    private $author;

我想和他的作者一起买一本书,以及这个作者写的所有书。这样我以后就可以遍历这组书籍。

问题是当我请求 url 时:

GET localhost:8001/api/books/1

响应如下:

{
    "@context": "/api/contexts/Book",
    "@id": "/api/books/1",
    "@type": "Book",
    "author": {
        "@id": "/api/authors/1",
        "@type": "Author",
        "books": [
            "/api/books/1",
            {
                "@id": "/api/books/2",
                "@type": "Book",
                "author": "/api/authors/1"
            }
        ]
    }
}

我想把书 1 作为一个对象,而不是一个 IRI,我搞砸了什么?

编辑:澄清一下,我期待的回应是:

{
    "@context": "/api/contexts/Book",
    "@id": "/api/books/1",
    "@type": "Book",
    "author": {
        "@id": "/api/authors/1",
        "@type": "Author",
        "books": [
            {
                "@id": "/api/books/1",
                "@type": "Book",
                "author": "/api/authors/1"
            },
            {
                "@id": "/api/books/2",
                "@type": "Book",
                "author": "/api/authors/1"
            }
        ]
    }
}

编辑:链接到测试回购

标签: symfonyapi-platform.com

解决方案


推荐阅读