How to check if find or findBy returns Null?

by Khaled Ouertani   Last Updated December 06, 2018 14:26 PM

I have two entities

  • Client
  • Info

with a one-to-one-unidirectional relationship, as a Client can have none or one Info.

I am trying to check if Client already has Info with this:

$em = $this->getDoctrine()->getManager();

$check = $em->getRepository("MyBundle:Info")>findBy(array(
    'client_id' => $id, 
));

Note that $id would be the client id I am already passing as a parameter and have access to. The question is what sort of data would $check would be so I can be able to verify it as shown below:

if ($check ??..) {
    //..do this
} else { 
    //.. do that
}


Answers 1


It is that simple. Use findOneBy(), which returns either an entity or null if the entity can not be found:

$em = $this->getDoctrine()->getManager();

$info = $em->getRepository("MyBundle:Info")->findOneBy([
    'client_id' => $id,
]);

if ($info) {
    // manipulate existing info
} else {
    // create new info
}

For reference, see:

svgrafov
svgrafov
August 14, 2017 09:20 AM

Related Questions


Updated August 30, 2017 06:26 AM

Updated November 19, 2017 22:26 PM

Updated March 17, 2017 19:26 PM

Updated March 22, 2017 12:26 PM

Updated August 26, 2017 10:26 AM