Skip to content

Best practice to include a COUNT query in collection operation #1083

Closed
@superbull

Description

@superbull

In case I have below Entities:

class Book
{
    private $id;
    private $title;
    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Review", mappedBy="book")
     */
    private $reviews;
}

class Review
{
    private $id;
    private $body;
    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Book", inversedBy="reviews")
     */
    private $book;
}

When I retrieve a list of Books, I want also the total number of the reviews a book contains. The response should like below:

{
  "hydra:member": [
    {
      "@id": "/books/e0820d66-81cd-4e48-8b09-f2931a39951b",
      "@type": "http://schema.org/Book",
      "title": "345",
      "reviewsCount": 20
    }
  ]
}

What is the right way to implement this in API Platform?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions