有关 jenssegers / Laravel-MongoDB 中 update 批量更新 单数据更新问题 (multiple)

目前环境:

  • laravel 5.2
  • mongodb 3.x
  • jenssegers / laravel-mongodb 3.0.2

遇到的问题:
在使用 jenssegers / laravel-mongodb 3.0.2 的 Eloquent方式进行操作Mongodb,但我发现update方法是批量更新的。也就是说满足where的所有数据都会被强制更新,曾经可以通过option中的multiple进行控制是更新一条数据还是更新满足条件的所有数据,但现在不可以!这是个bug吗...

有没有其他办法能够在update的时候,能够手动指定更新一条数据还是多条数据?


相关代码参考:
code:
vendor/jenssegers/mongodb/src/Jenssegers/Mongodb/Query/Builder.php

    /**
     * Update a record in the database.
     *
     * @param  array  $values
     * @param  array  $options
     * @return int
     */
    public function update(array $values, array $options = [])
    {
        // Use $set as default operator.
        if (! starts_with(key($values), '$')) {
            $values = ['$set' => $values];
        }

        return $this->performUpdate($values, $options);
    }

    /**
     * Perform an update query.
     *
     * @param  array  $query
     * @param  array  $options
     * @return int
     */
    protected function performUpdate($query, array $options = [])
    {
        // Update multiple items by default.
        if (! array_key_exists('multiple', $options)) {
            $options['multiple'] = true;
        }

        $wheres = $this->compileWheres();
        // 可以看到这里只用了UpdateMany方法,并没有考虑到UpdateOne
        $result = $this->collection->UpdateMany($wheres, $query, $options);
        if (1 == (int) $result->isAcknowledged()) {
            return $result->getModifiedCount() ? $result->getModifiedCount() : $result->getUpsertedCount();
        }

        return 0;
    }

继续进入UpdateMany方法:
vendor/mongodb/mongodb/src/Operation/UpdateMany.php

    public function __construct($databaseName, $collectionName, $filter, $update, array $options = [])
    {
        if ( ! is_array($update) && ! is_object($update)) {
            throw InvalidArgumentException::invalidType('$update', $update, 'array or object');
        }

        if ( ! \MongoDB\is_first_key_operator($update)) {
            throw new InvalidArgumentException('First key in $update argument is not an update operator');
        }

        $this->update = new Update(
            $databaseName,
            $collectionName,
            $filter,
            $update,
            // 这里一条multi => true给写死了 ... 
            ['multi' => true] + $options
        );
    }
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
讨论数量: 1

在项目里检索UpdateOne 也没找到有用的信息 ...
难道只能批量操作数据吗... :(

5年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!