Search code examples
phpsymfony1doctrine-inheritance

Symfony framework - check database entry existence


Using symfony framework, which code is best to query database table to check if entry is already there?

I need query like this:

$q = $this->createQuery('t')
    ->where('t.email = ?', $email)
    ->andWhere('t.type = ?','newsletter');

Solution

  • The easist way, assuming you're in a Doctrine_Table instance, which it appears you are is:

    $this->findOneByEmail($email);
    

    You shouldn't need type if you're using concrete inheritance because it will be added via DQL callback (assuming you have them enabled), but for completeness:

    $this->findOneByEmailAndType($email, 'newsletter');
    

    These will return the Doctrine_Record if it exists or null if it doesn't.

    You can also use a count on your query:

    $exists = $this->createQuery('t')
        ->where('t.email = ?', $email)
        ->andWhere('t.type = ?','newsletter') // your probably don't need this
        ->count();
    

    This will return either the number of records that match the query. This a more efficient as it does not hydrate the results.