0

I try to make a custom deletion logic via a custom repository:

namespace AppBundle\Repository;

use AppBundle\Entity\ContactEmail;

class ContactEmailRepository extends \Doctrine\ORM\EntityRepository
{
  /**
  * Remove an email from the database
  * @param String $email
  */
  public function deleteEmail($email)
  {
    $em=$this->getEntityManager();

    $queryBuilder = $em->createQueryBuilder();
    $queryBuilder->delete('AppBundle::ContactEmail','c')
      ->where('c.email=:email')
      ->setParameter('email',$email);

    $query=$queryBuilder->getQuery();

    $p = $query->execute();

    return $p;
  }
}

And I test it via a functional test:

namespace Tests\AppBundle\Repository;

use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use AppBundle\Entity\ContactEmail;
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
use Doctrine\ORM\Tools\SchemaTool;
Use Doctrine\Common\DataFixtures\Purger\ORMPurger;


use AppBundle\DataFixtures\ContactEmailDataFixture;



class ContactEmailTest extends KernelTestCase
{
/**
    * @var \Doctrine\ORM\EntityManager
    */
   private $entityManager;

   /**
    * {@inheritDoc}
    */
   protected function setUp()
   {
       $kernel = self::bootKernel();

       $this->entityManager = $kernel->getContainer()
           ->get('doctrine')
           ->getManager();

       //In case leftover entries exist
       $schemaTool = new SchemaTool($this->entityManager);
       $metadata = $this->entityManager->getMetadataFactory()->getAllMetadata();

       // Drop and recreate tables for all entities
       $schemaTool->dropSchema($metadata);
       $schemaTool->createSchema($metadata);
   }

   /**
   * Testing whether a preloaded email will get deleted
   */
   public function testDeletion()
   {
     $fixture = new ContactEmailDataFixture();
     $fixture->load($this->entityManager);

     /**
     * @var Appbundle\Repository\ContactEmailRepository
     */
     $repository=$this->entityManager->getRepository(ContactEmail::class);

     $emailToDelete='[email protected]';
     $repository->deleteEmail($emailToDelete);

     $emailSearched=$repository->findOneBy(['email'=>$emailToDelete]);
     $this->assertEmpty($emailSearched);
   }
}

My entity is the following:

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;

/**
 * ContactEmail
 *
 * @ORM\Table(name="contact_email")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\ContactEmailRepository")
 * @UniqueEntity("email")
 */
class ContactEmail
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
    * @var String
    * @ORM\Column(name="email",type="string",unique=true)
    * @Assert\Email( message = "The email '{{ value }}' is not a valid email.")
    */
    private $email;

    /**
    * @ORM\Column(name="date", type="datetime")
    */
    private $createdAt;

    public function __construct()
    {
      $this->createdAt=new \DateTime("now", new \DateTimeZone("UTC"));
    }

    /**
     * Get id
     *
     * @return int
    */
    public function getId()
    {
        return $this->id;
    }

    /**
    * @param String $email
    * @return ContactEmail
    */
    public function setEmail($email){
      $this->email=$email;

      return $this;
    }

    /**
    * @return String
    */
    public function getEmail(){
      return $this->email;
    }

    public function getCreatedAt()
    {
      return $this->createdAt;
    }
}

And I use the following DataFixture:

namespace AppBundle\DataFixtures;

use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\Persistence\ObjectManager;
use AppBundle\Entity\ContactEmail;

class ContactEmailDataFixture extends Fixture
{
    public function load(ObjectManager $manager)
    {
        $emails=['[email protected]','[email protected]','[email protected]'];
        foreach($emails as $email){
          $emailEntityInstance=new ContactEmail();
          $emailEntityInstance->setEmail($email);

          $manager->persist($emailEntityInstance);
          $manager->flush();
        }
    }
}

The problem is that I get the following error when I run the test:

Doctrine\ORM\Query\QueryException: [Semantical Error] line 0, col 7 near 'AppBundle::ContactEmail': Error: Class 'AppBundle\Entity\' is not defined.

So I want to know what I did wrong on the query syntax?

4
  • 1
    Kind of a strange error message. Just for kicks, try delete('ContactEmail::class','c') Commented Aug 18, 2018 at 12:50
  • That what you mentioned has worked. Perhaps it may need a full namespace class name in order to work. Commented Aug 18, 2018 at 13:12
  • Actually, I suspect dropping a colon and using AppBundle:ContractEmail would work as well. Was looking for an example but could not find one. The AppBundle alias dates back to before the ::class functionality was available and would save some typing. Nowadays, just use the fully qualified name and all should be well. Commented Aug 18, 2018 at 13:15
  • I think your entities were cached when you asked the question, but the cache expired when you trued the suggestion given by Dimitrios Desyllas. If you now try the same, what is the behavior you experience? You might want to empty the cache before you do tests with new entities, read more here: symfony.com/doc/3.3/console/usage.html Commented Aug 18, 2018 at 13:40

1 Answer 1

2

In a class that extends Doctrine\ORM\EntityRepository and that is referenced in the entity's @Entity docblock annotation's repositoryClass attribute, you can get a query builder like this:

$queryBuilder = $this->createQueryBuilder('c')
  ->where('c.email=:email')
  ->setParameter('email',$email);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.