How do I check if object was found in a Doctrine2 repository?

人走茶凉 提交于 2019-12-10 13:00:03

问题


I am finding a entity by its PK as follow:

$ent = $em->getRepository('AppBundle:Representative')->find($id)

What is the right way to check whether $ent is a real Representative object or not? What I mean with real is that $ent currently exists on DB and was returned since I am planning to use the same results for INSERT and UPDATE. In pseudo-code what is on my head is:

if (ent is Representative)
{
    // Update its values
} else {
    // Create a new Representative
}

I was thinking in use is_object() or even instanceof but I am not sure if they will do the job or if $ent will be an object even if Representative doesn't exist on DB. Any advice on this? How I can achieve that?


回答1:


EntityRepository::find() method (which you use) returns an object, or null if the object couldn't be found in the database. All of the following conditions are valid:

if ($entity) {
}

if (null !== $entity) {
}

if ($entity instanceof Representative) {
}

Choose one that suits your coding standards the best, and use it consistently.

If you don't need to create a new object if it's not found, better throw an exception and handle it appropriately.




回答2:


How about this:

$product = $this->getDoctrine()
        ->getRepository('AppBundle:Product')
        ->find($id);

    if (!$product) {
        throw $this->createNotFoundException(
            'No product found for id '.$id
        );

Source: click me



来源:https://stackoverflow.com/questions/31115825/how-do-i-check-if-object-was-found-in-a-doctrine2-repository

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!