Hello guys I just started using Api-Platform and I got stuck on this problem for several hours.
I have a Symfony4 Project and two Entities: Bill & Abo
Bill:
/**
 * @ORM\Entity(repositoryClass="App\Repository\BillRepository")
 * @ApiResource
 */
class Bill {
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;
    /**
     * @var \DateTime
     *
     * @ORM\Column(name="date", type="date", nullable=false)
     */
    private $date;
    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Abo", inversedBy="bills")
     * @ORM\JoinColumn
     * @ApiSubresource
     */
    private $abo;
}
Abo:
/**
 * @ORM\Entity(repositoryClass="App\Repository\AboRepository")
 * @ApiResource
 */
class Abo
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;
    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=50, nullable=false)
     */
    private $name;
    /**
     * @var integer
     *
     * @ORM\Column(name="price", type="integer", nullable=false)
     */
    private $price;
    /**
     * @ORM\OneToMany(targetEntity="App\Entity\Bill", mappedBy="abo")
     */
    private $bills;
}
When I now call this url, /api/bills, I get get back this data:
{
  "@id": "/api/bills/14",
  "@type": "Bill",
  "id": 14,
  "date": "2018-03-08T00:00:00+00:00",
  "abo": "/api/abos/1"
},
...
But instead of this "abo": "/api/abos/1" I want the Abo data already loaded, something like this:
"abo": {
    "name": "TestAbo",
    "price": 25
}
Is this possible and if yes how can I achieve this?
Thanks for your time and help!
You can use serialization groups for this. Make sure that your relation field $abo and it's member fields groups are exposed.
use Symfony\Component\Serializer\Annotation\Groups;
/**
 * @ORM\Entity(repositoryClass="App\Repository\BillRepository")
 * @ApiResource(attributes={
 *   "normalization_context"={"groups"={"bill", "bill-abo", "abo"}}
 * })
 */
class Bill {
  ...
  /**
   * @ORM\ManyToOne(targetEntity="App\Entity\Abo", inversedBy="bills")
   * @ORM\JoinColumn
   * @ApiSubresource
   * @Groups("bill-abo")
   */
   private $abo;
   ...
}
class Abo {
    ...
    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=50, nullable=false)
     * @Groups("abo")
     */
    private $name;
    ...
}
You can read more in the docs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With