Question

I'm not having any luck using merge(). I'm doing almost exactly what is documented:

/* @var $detachedDocument MyDocumentClass */ 
$detachedDocument = unserialize($serializedDocument);
$document = $dm->merge($detachedDocument);
$document->setLastUpdated(new \MongoDate());
$dm->persist($document);

but the change never sticks. I have to do this instead:

$dm->createQueryBuilder('MyDocumentClass')
    ->findAndUpdate()
    ->field('lastUpdated')->set(new \MongoDate())
    ->getQuery()
    ->execute();

merge() seems pretty straightforward, so I'm confused why it doesn't work like I think it should.

Was it helpful?

Solution

In your first code example, merge() followed by persist() is redundant, and you omitted a flush(), which is the only operation that would actually write to the database (unless you execute a query manually, as you did in the second example). If you walk through the code in UnitOfWork::doMerge(), you'll see that it's going to either persist the object (if it has no ID) or fetch the document by its ID. The end result is that merge() returns a managed document. Persist ensures that the document will be managed after it is called (it returns nothing itself). If you poke in UnitOfWork::doPersist(), you'll see that passing a managed object to the method is effectively a NOOP.

Try replacing persist() with flush(). Note that you can flush a single document if necessary, but $dm->flush() processes all managed objects by default.

If that still doesn't help, I'd confirm that the lastUpdated field is properly mapped in ODM. You can inspect the output of $dm->getClassMetadata('MyDocumentClass') to confirm. If it isn't a mapped field, UnitOfWork will detect no changes in the document and there will be nothing to flush.

As an aside: in the second code example, you're executing findAndUpdate() without any search criteria (only the set() is specified). Typically, you'd pair the modification with something like equals() (probably the ID in your case) to ensure that a single document is atomically modified and returned.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top