有一种方法可以自动更新所有相关字段?如果我知道所有数据发送,我可以这样做:
return $this->dm->createQueryBuilder(Product::class)
->findAndUpdate()
->field('_id')->equals($data['id'])
->field('author_id')->equals($id)
->field('known_fields')->set($data['known_fields'])
->getQuery()
->execute();
但如果$data发生变化,例如:
$data['known_field' => '...', 'unknown_field' => '...']
为了解决问题,我这样做,
public function update(String $id, $data)
{
try {
$query = $this->dm->createQueryBuilder(Product::class)
->findAndUpdate()
->field('_id')->equals($data['id'])
->field('author_id')->equals($id);
$this->updateFields($query, $data)
->getQuery()
->execute();
} catch (MongoDBException $e) {
return new JsonResponse(['message' => $e->getMessage()]);
}
}
public function updateFields(Builder $dm, $data)
{
unset($data['id'], $data['author_id']);
foreach ($data as $key => $field) {
$dm->field($key)->set($field);
}
return $dm;
}
但是没有另一个美丽的解决方案吗? 也许像这样:
return $this->dm->createQueryBuilder(Product::class)
->findAndUpdate()
->field('_id')->equals($data['id'])
->field('author_id')->equals($id)
->sets(['field' => 'value', 'field_2' => 'value_2', ...])
->getQuery()
->execute();
无法在 ODM 中设置要更新的多个字段。编写自己的循环是正确的方法。