如何检查find或findBy是否返回Null?

时间:2017-08-14 09:09:24

标签: php symfony doctrine-orm

我有两个实体

  • Client
  • Info

具有一对一的单向关系,因为Client可以没有或只有一个Info

我正在尝试检查Client是否已经Info

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

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

请注意,$id将是我已作为参数传递并有权访问的客户端ID。问题是$check将会是什么类型的数据,以便我能够验证它,如下所示:

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

1 个答案:

答案 0 :(得分:4)

就这么简单。使用findOneBy(),如果无法找到实体,则返回实体或null

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

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

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

供参考,见: