开发者

Doctrine (Mongo) Persisting Partial Document

I have a custom class that populates a controller's action parameters based on the typehint of the parameter. This works well for documents (using public properties and setters).

My aim is to make the controller simple:

function updateAction(Article $article)
{
    $dm = new DocumentManager(); // code elsewhere
    $dm->merge($article);
    $dm->flush();

    return $this->redirect('/article/' . $article->getId());
}

The problem is that the input supplying the fields to programatically populate the Article class doesn't contain all of the properties of an Article class (perhaps the edit form only contains Title and Content, but disregards Author, etc).

I was hoping that the presence of an ID would allow the document to be merged gracefully with what is currently in the database. However, any fields that are mi开发者_如何学Gossing at the time of a merge will be removed from the document in the database.

Is there a way to update a document in such a way that only the fields that are present (non-null, I guess) are updated?


Rather than hitting the db twice - once for the find, and once for the update, you can use a FIND_AND_UPDATE query.and do it all in one step.

See this docs page for details: http://docs.doctrine-project.org/projects/doctrine-mongodb-odm/en/latest/reference/find-and-update.html


It seems that a clean way would be to bind the model AFTER retrieving it from the database. Something along the lines of ASP.NET MVC's UpdateModel.

function updateAction($id)
{
    $dm = new DocumentManager(); // code elsewhere

    $article = $dm->getRepository('Article')->find($id);
    $this->updateModel($article);
    $dm->flush();

    return $this->redirect('/article/' . $article->getId());
}

If there are any better suggestions, feel free to answer...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜