0

There is a way for automatically update all relevant fields ? If I know all data send, I can do this :

 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();

but if $data change, for example :

$data['known_field' => '...', 'unknown_field' => '...']

to solve the problem I do this,

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;
    }

but there is not an another beautiful solution ? maybe like this :

 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();
cisco_bro
  • 81
  • 2
  • 7

1 Answers1

0

There is no way to set several fields to update in the ODM. Writing your own loop is correct approach.

malarzm
  • 2,831
  • 2
  • 15
  • 25