温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Laravel中自增实现方案

发布时间:2020-07-20 18:51:35 来源:网络 阅读:858 作者:liuxu1992 栏目:web开发

工作中经常会对一列数据进行自增操作,设想一个场景。
总共发放10张优惠券(以下的操作以时间为序列)
1)用户1请求领取1张优惠券;
2)进程1查询到数据库中剩余10张,代码更新优惠券数量,此时为内存中优惠券数量为9;
3)此时,用户2请求领取1张优惠券。进程1并未将9写入到数据库中,所以此时进程2取到的优惠券的数量还是10。进程2计算数量,内存中的优惠券数量为9;
4)进程1更新数据库优惠券的数量,number = 9;
5)进程2更新数据库优惠券的数量,number = 9;
实际上已经发出去了两张优惠券,但是数据库中还剩9张优惠券。

所以呢,将数据load到内存中加减完成再入库是有点风险的。
两种解决方案:
1)加锁,别管是加个乐观锁还是悲观锁,这个不细聊了;
2)不在内存中加,直接在数据库层面进行set number = number - 1;在Laravel中,有increment和decrement封装来实现操作。
increment:

public function increment($column, $amount = 1, array $extra = [])
{
        if (! is_numeric($amount)) {
                throw new InvalidArgumentException('Non-numeric value passed to increment method.');
        }
        $wrapped = $this->grammar->wrap($column);
        $columns = array_merge([$column => $this->raw("$wrapped + $amount")], $extra);
        return $this->update($columns);
}

decrement:

public function decrement($column, $amount = 1, array $extra = [])
{
        if (! is_numeric($amount)) {
                throw new InvalidArgumentException('Non-numeric value passed to decrement method.');
        }
        $wrapped = $this->grammar->wrap($column);
        $columns = array_merge([$column => $this->raw("$wrapped - $amount")], $extra);
        return $this->update($columns);
}

都调用了update方法,看一下update:

public function update(array $values)
    {
        $sql = $this->grammar->compileUpdate($this, $values);
        var_dump($sql); // 打印一下sql语句
        return $this->connection->update($sql, $this->cleanBindings(
            $this->grammar->prepareBindingsForUpdate($this->bindings, $values)
        ));
    }

用两种方式进行数据库修改:
1)直接修改数量

$res = self::where('id', $data['id'])->update(['number' => self::raw('number + 1')] );

查看输出的sql语句:

 update  coupon  set  number  =  ?  where  id  = ?

2)用decrement

$res = self::where('id', $data['id'])->decrement('number', 2);

查看sql输出结果:

update coupon set number = number - 2 where id = ?;

所以并发较多的情况下建议使用increment和decrement。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI