Aboy
Aboy

Reputation: 11

Symfony 4 relation ManyToOne return only id not the whole objet

hello I have two entity Patient and Appointement I work with Api platform and the relation between Appointement and Patient is ManyToOne when I try to get Appointement I get only the id of patient not the whole objet

My function get

/**
 * @Route("/appointement", methods={"GET"})
 */
public function findAppointement(AppointementRepository $appointementRepository,SerializerInterface $serializer)
{
    //AVOIR AU MOINS LE ROLE_SECRETAIRE POUR RECUPERER LES  APPOINTEMENT
    $this->denyAccessUnlessGranted('ROLE_SECRETAIRE',null,"Accès non autorisé");

    $appointement= $appointementRepository->findAll();
    $data=$serializer->serialize($appointement,"json", [
        'circular_reference_handler' => function ($object) {
            return $object->getId();
        }
    ]);
    return new JsonResponse($data,Response::HTTP_OK,[],true);
}

My Patient entity

/**
 * @ORM\OneToMany(targetEntity="App\Entity\Appointement", mappedBy="patient")
 */
private $appointements;

/**
 * @ORM\OneToMany(targetEntity="App\Entity\PatientData", mappedBy="patient")
 */
private $patientData;

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

My Appointement entity

/**
 * @ORM\ManyToOne(targetEntity="App\Entity\Patient", inversedBy="appointements")
 * @ORM\JoinColumn(nullable=false)
 */
private $patient;

thank you

Upvotes: 0

Views: 100

Answers (1)

Dylan KAS
Dylan KAS

Reputation: 5663

You are only getting the id because you defined your circular_reference_handler to only get the id. You can modify it and get more information from your patient.

$data=$serializer->serialize($appointement,"json", [
    'circular_reference_handler' => function ($object) {
        if($object instanceof Patient){
            return ['value1' => $object->getValue1(), 'value2' => $object->getValue2()]
        }
        return $object->getId();
    }
]);

Upvotes: 1

Related Questions