tags:

views:

49

answers:

1

I've come across this scenario a few times in working on a current project. I have to see if a record exists then if it doesn't I need to add it, if it does then I need to update. What is the standard way of doing this with Doctrine?

I seem to be querying to see if the record exists using a find* method. Then if that returns a positive result (object), I use that object to update. Otherwise, (no record found) I have to create another object and save().

For some reason this just seems inefficient. Is there a better way or am I just being weird? :)

$user = Doctrine_Core::getTable('Model_User')->findOneByEmail('[email protected]');
if (!$user) {
    $user = new Model_User();
    $user->fromArray($values); // $values comes from form or wherever
    $user->save();
} else {
    $user->fromArray($values);
    $user->save();
}
+1  A: 

It seems to be that you're just making it a little verbose :) This is pretty "clean" I think:

$user = Doctrine_Core::getTable('Model_User')->findOneByEmail('[email protected]');
if (!$user) {
    $user = new Model_User();
}
$user->fromArray($values); // $values comes from form or wherever
$user->save();

You could roll your own:

class Model_UserTable extends Doctrine_Table {
    ...

    public findOrCreateOneByEmail($email) {
        $user = $this->findOneByEmail($email);
        if (is_null($user)) {
            $user = new Model_User();
            $user->email = $email;
        }

        return $user;
    }
}
jensgram
Yeah, I guess you are right. I like the first option. Not sure why I duplicated the save() code.
Jeremy Hicks
I find this specific kind of "utility" functions to be more disturbing than helpful, too :)
jensgram