Yii2 字段自增或自减
2018-07-31 13:48 浏览(6510

用Yii2的时候需要自增或自减某个字段的值,往往都是先find出来,然后增加,再save,操作了两次数据库,有点得不偿失。

网上百度了也没找到简单的实现方法,要么就是根本能用,然后就自己看源码,最后在 ActiveRecord 中找到了一个 updateAllCounters 方法

/**
     * Updates the whole table using the provided counter changes and conditions.
     * For example, to increment all customers' age by 1,
     *
     * ~~~
     * Customer::updateAllCounters(['age' => 1]);
     * ~~~
     *
     * @param array $counters the counters to be updated (attribute name => increment value).
     * Use negative values if you want to decrement the counters.
     * @param string|array $condition the conditions that will be put in the WHERE part of the UPDATE SQL.
     * Please refer to [[Query::where()]] on how to specify this parameter.
     * @param array $params the parameters (name => value) to be bound to the query.
     * Do not name the parameters as `:bp0`, `:bp1`, etc., because they are used internally by this method.
     * @return integer the number of rows updated
     */
    public static function updateAllCounters($counters, $condition = '', $params = [])
    {
        $n = 0;
        foreach ($counters as $name => $value) {
            $counters[$name] = new Expression("[[$name]]+:bp{$n}", [":bp{$n}" => $value]);
            $n++;
        }
        $command = static::getDb()->createCommand();
        $command->update(static::tableName(), $counters, $condition, $params);

        return $command->execute();
    }

使用很简单

User::updateAllCounters(['point' => 8],'id=1');

给用户id为1的用户增加8积分,若是要减少的话,设置为负数即可

评论(1)
发布评论
回复X
聊天室(0