tags:

views:

79

answers:

2

whenever i insert a entity that already exists in database (i have a unique constraint on email) i get an error message on the screen.

so i want to check if it already exists, if not i insert it.

at the moment it looks like this:

$q = Doctrine_Query::create()
    ->from('User u')
    ->where('u.email = ?', $email);

$object = $q->fetchOne();

if( ! is_object($object)) {
          $user = new User();
          $user-email = $email;
          $user->save();
    }

i wonder, if there an easier way to do this?

thanks

A: 

you could handle the insert error

drscroogemcduck
could u explain how?
never_had_a_name
+1  A: 

Put the code you have into a method in your UserTable class eg insertIfNotExists():

public function insertIfNotExists(User $user)
{
  // Check if it exists first
  $q = self::create("u")
    ->where("u.email = ?", $user->email)
    ->execute();

  // Do we have any?
  if ($q->count())
  {
    // Yes, return the existing one
    return $q->getFirst();
  }

  // No, save and return the newly created one
  $user->save();
  return $user;
}

Now you can call the method, and the object returned will be the existing record (if there is one), or the one you've just created.

richsage