How to use getQuery()->getOneOrNullresult() return

18,671

getOneOrNullResult method tells you if any record in database is found, or not. If it return null, it means that you have some results, and in your case you have to insert new one. But when it exists some records, this method will return object instance of your entity. That means in your case you have to update existing record.

Please remember, that getOneOrNullResult method throws exception, when result set is not unique.

Share:
18,671
MyLaboDev
Author by

MyLaboDev

Updated on June 04, 2022

Comments

  • MyLaboDev
    MyLaboDev almost 2 years

    in my test project I have 2 entities : - endUser (extend of FOSUserBundle) - Rezo (will containt approved relation between two members)

    the both entities have been defined as :

    EndUser Entity :

    <?php
    
    namespace Core\CustomerBundle\Entity;
    
    use Doctrine\ORM\Mapping as ORM;
    use FOS\UserBundle\Model\User as BaseUser;
    use Symfony\Component\Validator\Constraints as Assert;
    
    
    /**
     * EndUser
     *
     * @ORM\Table()
     * @ORM\Entity(repositoryClass="Core\CustomerBundle\Entity\EndUserRepository")
     */
    class EndUser extends BaseUser
    {
        /**
         * @var integer
         *
         * @ORM\Column(name="id", type="integer")
         * @ORM\Id
         * @ORM\GeneratedValue(strategy="AUTO")
         */
        protected $id;
    
        /**
         * @var string
         * @ORM\Column(name="firstname", type="string", length=255)
         */
        private $firstname;
    
        /**
         * @var string
         * @ORM\Column(name="lastname", type="string", length=255)
         */
        private $lastname;
    
        /**
         * @var \DateTime
         *
         * @ORM\Column(name="DateNaissance", type="datetime", nullable=true)
         */
        private $DateNaissance;
    
        /**
         * @ORM\OneToOne(targetEntity="Core\CustomerBundle\Entity\EndUser", cascade={"persist", "merge", "remove"})
         * @ORM\JoinColumn(name="adressbook_id", referencedColumnName="id", nullable=true)
         */
        private $adressbook;
    
        /**
         * @ORM\ManyToMany(targetEntity="Core\MyEquiBookBundle\Entity\Discipline", mappedBy="endusers")
         */
        private $disciplines;
    
        /**
         * @ORM\ManyToMany(targetEntity="Core\MyEquiBookBundle\Entity\Experiences", mappedBy="endusers")
         */
        private $experiences;
    
        /**
         * @var string
         * @ORM\Column(name="avatar", type="string", length=255, nullable=true)
         */
        private $avatar;
    
        /**
         * @var string
         * @ORM\Column(name="repository", type="string", length=255, nullable=true)
         */
        private $repository;
    
        /**
         * @ORM\OneToMany(targetEntity="Core\MyEquiBookBundle\Entity\NiveauEndUser", mappedBy="enduser", cascade={"remove", "persist"})
         */
        protected $niveaux;
    
        /**
         * @ORM\OneToMany(targetEntity="Core\GeneralBundle\Entity\Rezo", mappedBy="enduser", cascade={"remove", "persist"})
         */
        protected $friends;
    
        /**
         * Constructor
         */
        public function __construct()
        {
            parent::__construct();
            $this->disciplines = new \Doctrine\Common\Collections\ArrayCollection();
            $this->niveaux = new \Doctrine\Common\Collections\ArrayCollection();
            $this->experiences = new \Doctrine\Common\Collections\ArrayCollection();
            $this->friends = new \Doctrine\Common\Collections\ArrayCollection();
            $this->expiresAt = new \DateTime("+1 year");
            $this->credentialsExpireAt = new \DateTime("+1 year");
        }
    
        /**
         * Get id
         *
         * @return integer 
         */
        public function getId()
        {
            return $this->id;
        }
    
        /**
         * Set avatar
         *
         * @param string $avatar
         * @return EndUser
         */
        public function setAvatar($avatar)
        {
            $this->avatar = $avatar;
    
            return $this;
        }
    
        /**
         * Get avatar
         *
         * @return string 
         */
        public function getAvatar()
        {
            return $this->avatar;
        }
    
        /**
         * Set repository
         *
         * @param string $repository
         * @return EndUser
         */
        public function setRepository($repository)
        {
            $this->repository = $repository;
    
            return $this;
        }
    
        /**
         * Get repository
         *
         * @return string 
         */
        public function getRepository()
        {
            return $this->repository;
        }
    
        /**
         * Set adressbook
         *
         * @param \Core\CustomerBundle\Entity\EndUser $adressbook
         * @return EndUser
         */
        public function setAdressbook(\Core\CustomerBundle\Entity\EndUser $adressbook = null)
        {
            $this->adressbook = $adressbook;
    
            return $this;
        }
    
        /**
         * Get adressbook
         *
         * @return \Core\CustomerBundle\Entity\EndUser 
         */
        public function getAdressbook()
        {
            return $this->adressbook;
        }
    
        /**
         * Add disciplines
         *
         * @param \Core\MyEquiBookBundle\Entity\Discipline $disciplines
         * @return EndUser
         */
        public function addDiscipline(\Core\MyEquiBookBundle\Entity\Discipline $disciplines)
        {
            $this->disciplines[] = $disciplines;
    
            return $this;
        }
    
        /**
         * Remove disciplines
         *
         * @param \Core\MyEquiBookBundle\Entity\Discipline $disciplines
         */
        public function removeDiscipline(\Core\MyEquiBookBundle\Entity\Discipline $disciplines)
        {
            $this->disciplines->removeElement($disciplines);
        }
    
        /**
         * Get disciplines
         *
         * @return \Doctrine\Common\Collections\Collection 
         */
        public function getDisciplines()
        {
            return $this->disciplines;
        }
    
        /**
         * Add niveaux
         *
         * @param \Core\MyEquiBookBundle\Entity\NiveauEndUser $niveaux
         * @return EndUser
         */
        public function addNiveaux(\Core\MyEquiBookBundle\Entity\NiveauEndUser $niveaux)
        {
            $this->niveaux[] = $niveaux;
    
            return $this;
        }
    
        /**
         * Remove niveaux
         *
         * @param \Core\MyEquiBookBundle\Entity\NiveauEndUser $niveaux
         */
        public function removeNiveaux(\Core\MyEquiBookBundle\Entity\NiveauEndUser $niveaux)
        {
            $this->niveaux->removeElement($niveaux);
        }
    
        /**
         * Get niveaux
         *
         * @return \Doctrine\Common\Collections\Collection 
         */
        public function getNiveaux()
        {
            return $this->niveaux;
        }
    
        /**
         * Add experiences
         *
         * @param \Core\MyEquiBookBundle\Entity\Experiences $experiences
         * @return EndUser
         */
        public function addExperience(\Core\MyEquiBookBundle\Entity\Experiences $experiences)
        {
            $this->experiences[] = $experiences;
    
            return $this;
        }
    
        /**
         * Remove experiences
         *
         * @param \Core\MyEquiBookBundle\Entity\Experiences $experiences
         */
        public function removeExperience(\Core\MyEquiBookBundle\Entity\Experiences $experiences)
        {
            $this->experiences->removeElement($experiences);
        }
    
        /**
         * Get experiences
         *
         * @return \Doctrine\Common\Collections\Collection 
         */
        public function getExperiences()
        {
            return $this->experiences;
        }
    
        /**
         * Add friends
         *
         * @param \Core\GeneralBundle\Entity\Rezo $friends
         * @return EndUser
         */
        public function addFriend(\Core\GeneralBundle\Entity\Rezo $friends )
        {
            $this->friends[] = $friends;
    
            return $this;
        }
    
        /**
         * Remove friends
         *
         * @param \Core\GeneralBundle\Entity\Rezo $friends
         */
        public function removeFriend(\Core\GeneralBundle\Entity\Rezo $friends)
        {
            $this->friends->removeElement($friends);
        }
    
        /**
         * Get friends
         *
         * @return \Doctrine\Common\Collections\Collection 
         */
        public function getFriends()
        {
            return $this->friends;
        }
    
        /**
         * Set firstname
         *
         * @param string $firstname
         * @return EndUser
         */
        public function setFirstname($firstname)
        {
            $this->firstname = $firstname;
    
            return $this;
        }
    
        /**
         * Get firstname
         *
         * @return string 
         */
        public function getFirstname()
        {
            return $this->firstname;
        }
    
        /**
         * Set lastname
         *
         * @param string $lastname
         * @return EndUser
         */
        public function setLastname($lastname)
        {
            $this->lastname = $lastname;
    
            return $this;
        }
    
        /**
         * Get lastname
         *
         * @return string 
         */
        public function getLastname()
        {
            return $this->lastname;
        }
    
        /**
         * Set DateNaissance
         *
         * @param \DateTime $dateNaissance
         * @return EndUser
         */
        public function setDateNaissance($dateNaissance)
        {
            $this->DateNaissance = $dateNaissance;
    
            return $this;
        }
    
        /**
         * Get DateNaissance
         *
         * @return \DateTime 
         */
        public function getDateNaissance()
        {
            return $this->DateNaissance;
        }
    }
    

    Rezo Entity :

    <?php
    
    namespace Core\GeneralBundle\Entity;
    
    use Doctrine\ORM\Mapping as ORM;
    
    /**
     * Rezo
     *
     * @ORM\Table()
     * @ORM\Entity(repositoryClass="Core\GeneralBundle\Entity\RezoRepository")
     */
    class Rezo
    {
        /**
         * @var integer
         *
         * @ORM\Column(name="id", type="integer")
         * @ORM\Id
         * @ORM\GeneratedValue(strategy="AUTO")
         */
        private $id;
    
        /**
         * @var \DateTime
         *
         * @ORM\Column(name="RequestedDate", type="datetime")
         */
        private $requestedDate;
    
        /**
         * @var \DateTime
         *
         * @ORM\Column(name="AcceptedDate", type="datetime", nullable=true)
         */
        private $acceptedDate;
    
    
        /**
         * @ORM\ManyToOne(targetEntity="Core\CustomerBundle\Entity\Enduser", inversedBy="friends", cascade={"refresh"})
         * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
         */
        protected $enduser;
    
        /**
         * @ORM\ManyToOne(targetEntity="Core\CustomerBundle\Entity\EndUser", cascade={"refresh"})
         * @ORM\JoinColumn(name="friendwith", referencedColumnName="id")
         */
        protected $friendwith;
    
    
        /**
         * Get id
         *
         * @return integer 
         */
        public function getId()
        {
            return $this->id;
        }
    
        /**
         * Set requestedDate
         *
         * @param \DateTime $requestedDate
         * @return Rezo
         */
        public function setRequestedDate($requestedDate)
        {
            $this->requestedDate = $requestedDate;
    
            return $this;
        }
    
        /**
         * Get requestedDate
         *
         * @return \DateTime 
         */
        public function getRequestedDate()
        {
            return $this->requestedDate;
        }
    
        /**
         * Set acceptedDate
         *
         * @param \DateTime $acceptedDate
         * @return Rezo
         */
        public function setAcceptedDate($acceptedDate)
        {
            $this->acceptedDate = $acceptedDate;
    
            return $this;
        }
    
        /**
         * Get acceptedDate
         *
         * @return \DateTime 
         */
        public function getAcceptedDate()
        {
            return $this->acceptedDate;
        }
    
        /**
         * Set enduser
         *
         * @param \Core\CustomerBundle\Entity\EndUser $enduser
         * @return Rezo
         */
        public function setEnduser(\Core\CustomerBundle\Entity\EndUser $enduser = null)
        {
            $this->enduser = $enduser;
    
            return $this;
        }
    
        /**
         * Get enduser
         *
         * @return \Core\CustomerBundle\Entity\EndUser 
         */
        public function getEnduser()
        {
            return $this->enduser;
        }
    
        /**
         * Set friendwith
         *
         * @param \Core\CustomerBundle\Entity\EndUser $friendwith
         * @return Rezo
         */
        public function setFriendwith(\Core\CustomerBundle\Entity\EndUser $friendwith = null)
        {
            $this->friendwith = $friendwith;
    
            return $this;
        }
    
        /**
         * Get friendwith
         *
         * @return \Core\CustomerBundle\Entity\EndUser 
         */
        public function getFriendwith()
        {
            return $this->friendwith;
        }
    

    when I run :

    app/console doctrine:schema:update --force

    The following MySQL table has been created : 
    
    CREATE TABLE IF NOT EXISTS `Rezo` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `user_id` int(11) DEFAULT NULL,
      `friendwith` int(11) DEFAULT NULL,
      `RequestedDate` datetime NOT NULL,
      `AcceptedDate` datetime DEFAULT NULL,
      PRIMARY KEY (`id`),
      KEY `IDX_681FC4BA76ED395` (`user_id`),
      KEY `IDX_681FC4B1094AD75` (`friendwith`)
    ) ENGINE=InnoDB  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
    

    In the RezoController.php controller I would like to give to endUser opportunity to accept a contact request fot this I have created a function named : acceptnewrequestAction($id)

    public function acceptnewrequestAction($id){
    
            $em = $this->getDoctrine()->getManager();
            $rezo = $em->getRepository('CoreGeneralBundle:Rezo')->find($id);
            $user1 = $rezo->getEnduser();
            $user2 = $rezo->getFriendwith();
            $dateRequest = $rezo->getRequestedDate();
            $rezo->setAcceptedDate(new \DateTime('now'));
            $em->persist($rezo);
            $em->flush();
    
            /* check if inverse relation exist */
    
            $query = $em->CreateQuerybuilder();
            $query->select('t0.id');
            $query->from('CoreGeneralBundle:Rezo','t0');
            $query->where('t0.acceptedDate IS NULL');
            $query->andWhere('t0.enduser = :userId');
            $query->andWhere('t0.friendwith =:userId2');
            $query->SetParameters(array('userId'=> $user2, 'userId2'=>$user1));
            $result = $query->getQuery()->getOneOrNullResult();
    
            if ( is_object($result))
            {
                $rezo = $em->getRepository('CoreGeneralBundle:Rezo')->findById($result->getId());
                $rezo->setAcceptedDate(new \DateTime('now'));
             } else {
                $rezo = new Rezo();
                $rezo->setRequestedDate(new \Datetime('now'));
                $rezo->setAcceptedDate(new \DateTime('now'));
                $rezo->Setenduser($user2);
                $rezo->setFriendwith($user1);
            }
            $em->persist($rezo);
            $em->flush();
    
    
            return $this->render(controller('CoreGeneralBundle:Rezo:RezoList'));
        }
    

    I would like to know how I can use results to know if one object if found or return is Null and in case it exists update it or create a new one.

    thank you for your help

    • Cerad
      Cerad over 9 years
      @michail_w answer is correct. A simple if ($result) will suffice. I just wanted to point out that you may as well get the entire bezo object. That will eliminate the need to do a second find to update the accepted date.
    • Cerad
      Cerad over 9 years
      And if really just want to get an id then take a look at getScalerResult and getSingleScalerResult. They will be a tad bit faster since no object creation is required. docs.doctrine-project.org/en/latest/reference/…
  • MyLaboDev
    MyLaboDev over 9 years
    thank you for your feedback. I've modified my test as "if (result){...} - I have the following Error when result is not null :"Error: Call to a member function setAcceptedDate() on a non-object in /Applications/XAMPP/xamppfiles/htdocs/myequibook/src/Core/Ge‌​neralBundle/Controll‌​er/RezoController.ph‌​p line 96"? - but when result is null a new one is created as well :(
  • michail_w
    michail_w over 9 years
    You should use findOneById, not findById. First should return proper object, second should return something weird, I'm not shure if that method exists.
  • MyLaboDev
    MyLaboDev over 9 years
    I used FindOneBy($result) and it works. thank you for your help.