开发者

Doctrine - best way to check for a record, then either update or add

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? :)

$u开发者_JS百科ser = Doctrine_Core::getTable('Model_User')->findOneByEmail('myemail@email.com');
if (!$user) {
    $user = new Model_User();
    $user->fromArray($values); // $values comes from form or wherever
    $user->save();
} else {
    $user->fromArray($values);
    $user->save();
}


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('myemail@email.com');
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;
    }
}


I've wrote my own method in the needed sfDoctrineRecord class.

public function saveOrUpdate(Doctrine_Connection $conn = null) {
    $object = Doctrine_Core::getTable('TableAlias')->find(array($this->getKey1(), $this->getKey2()));
    if (!is_object($object)) {
        $object = $this;
    }else{
        $object->setVar1($this->getVar1());
        $object->setVar2($this->getVar2());
        $object->setVar3($this->getVar3());
        $object->setVar4($this->getVar4());
    }
    $object->save();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜