Announcement

Collapse
No announcement yet.

How to check if entity exists

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • How to check if entity exists

    I am trying to determine if an entity with certain fields exists by doing this:

    PHP Code:
    53         # Get the latest timesheet
     
    54         $lastTimesheet $this->getEntityManager()->getRepository('Timesheet')->where(array(
     
    55           'assignedUserId' => $userId
     56         
    ))->order('createdAt'true)->limit(01)->find();
     
    57
     58         
    if($lastTimesheet) {
     
    59           $GLOBALS['log']->error('-E- lastTimesheet: '$lastTimesheet->toArray());
     
    60         } else {
     
    61           $GLOBALS['log']->error('-E- No lastTimesheet: ', []);
     
    62         
    However, the `else` statement never executes. How do I determine if an entity exists? The `find` method will return an object regardless of what it actually finds, so my current code doesn't work. I looked in application/Espo/ORM/Entity.php, but I couldn't find any functions that would help determine if the entity actually exists.

  • #2
    I figured it out. You have to look in ORM/EntityCollection.php for the functions as find returns a collection.

    PHP Code:
    if(count($lastTimesheet)) {
      ...

    Comment


    • #3
      Hello
      Instead of limit(0, 1)->find() (it returns a collection), use findOne() (returns the object)

      Comment


      • #4
        Ok, thanks. If findOne is used, I think I have to do if($obj == null)and if I use find then I should check with if($collection->count()), right?

        Comment


        • #5
          EspoCRM – Open Source CRM Application. Contribute to espocrm/espocrm development by creating an account on GitHub.

          there you can see the main source code (find and findOne methods)

          Comment


          • #6
            Originally posted by tanya View Post
            https://github.com/espocrm/espocrm/b...tories/RDB.php
            there you can see the main source code (find and findOne methods)
            Thanks for the link and help. I'm mostly asking how to check if the object/collection exists after the query returns. Trying to use methods if the object is null or if the collection has no objects can cause an exception. That's what I'm trying to avoid, but I think I got it.

            PHP Code:

            $obj 
            = ...->findOne();
            if(
            $obj) {
              ...
            }

            $collection = ...->find();
            if(
            $collection->count()) {
              ...

            Comment


            • #7
              findOne() > if ($obj)
              find() > if($collection->count()) or if(count($collection)) - work the same

              Comment

              Working...
              X