如何使用其他字段的值更新字段? 例如,我想使用字段created_at的值更新字段updated_at(就像克隆字段一样)
$dm->createQueryBuilder('MyBundle:MyService')
->update()
->multiple(true)
->field('updated_at')->set(CREATED_AT_ATRIBUTE)
->getQuery()
->execute();
由于
答案 0 :(得分:0)
选项#1:应用程序端更新
使用Doctrine ODM时最简单的方法是在应用程序端执行更新。因此,您获取要更新的所有对象,进行必要的调整并刷新它们。
$services = $dm->createQueryBuilder('MyBundle:MyService')
->getQuery()
->execute();
foreach ($services as $service) {
$service->setUpdatedAt($service->getCreatedAt());
}
$db->flush();
$services
表示mongo游标,它将在您迭代时获取文档。如果您想立即从集合中获取所有文档,可以将eagerCursor
设置为true
。
选项#2:数据库端更新
您也可以直接在数据库本身上执行更新。但是,要执行此操作,您需要自己创建查询,因为查询构建器不支持此功能。
// Get MongoDB instance from DocumentManager
$mongo = $dm->getDocumentDatabase('Fully/Qualified/Class/Name')
->getMongoDB();
// Iterate over the collection and update each document
$mongo->execute('
db.MyServiceCollection.find().forEach(function (item) {
db.MyServiceCollection.update(
{_id: item._id},
{$set: {updated_at: item.created_at}}
);
});
');
forEach
中使用的函数只是一个常规的javascript函数,因此如果您需要对更新内容进行更多控制,可以在其中插入更多逻辑。