简体   繁体   中英

Doctrine ODM - Updated fields provided

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM