工作中經(jīng)常會對一列數(shù)據(jù)進(jìn)行自增操作,設(shè)想一個場景。
總共發(fā)放10張優(yōu)惠券(以下的操作以時間為序列)
1)用戶1請求領(lǐng)取1張優(yōu)惠券;
2)進(jìn)程1查詢到數(shù)據(jù)庫中剩余10張,代碼更新優(yōu)惠券數(shù)量,此時為內(nèi)存中優(yōu)惠券數(shù)量為9;
3)此時,用戶2請求領(lǐng)取1張優(yōu)惠券。進(jìn)程1并未將9寫入到數(shù)據(jù)庫中,所以此時進(jìn)程2取到的優(yōu)惠券的數(shù)量還是10。進(jìn)程2計算數(shù)量,內(nèi)存中的優(yōu)惠券數(shù)量為9;
4)進(jìn)程1更新數(shù)據(jù)庫優(yōu)惠券的數(shù)量,number = 9;
5)進(jìn)程2更新數(shù)據(jù)庫優(yōu)惠券的數(shù)量,number = 9;
實(shí)際上已經(jīng)發(fā)出去了兩張優(yōu)惠券,但是數(shù)據(jù)庫中還剩9張優(yōu)惠券。
成都創(chuàng)新互聯(lián)專注于鶴峰企業(yè)網(wǎng)站建設(shè),響應(yīng)式網(wǎng)站建設(shè),商城建設(shè)。鶴峰網(wǎng)站建設(shè)公司,為鶴峰等地區(qū)提供建站服務(wù)。全流程定制網(wǎng)站設(shè)計,專業(yè)設(shè)計,全程項(xiàng)目跟蹤,成都創(chuàng)新互聯(lián)專業(yè)和態(tài)度為您提供的服務(wù)
所以呢,將數(shù)據(jù)load到內(nèi)存中加減完成再入庫是有點(diǎn)風(fēng)險的。
兩種解決方案:
1)加鎖,別管是加個樂觀鎖還是悲觀鎖,這個不細(xì)聊了;
2)不在內(nèi)存中加,直接在數(shù)據(jù)庫層面進(jìn)行set number = number - 1;在Laravel中,有increment和decrement封裝來實(shí)現(xiàn)操作。
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);
}
都調(diào)用了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)
));
}
用兩種方式進(jìn)行數(shù)據(jù)庫修改:
1)直接修改數(shù)量
$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輸出結(jié)果:
update coupon set number = number - 2 where id = ?;
所以并發(fā)較多的情況下建議使用increment和decrement。
本文標(biāo)題:Laravel中自增實(shí)現(xiàn)方案
當(dāng)前鏈接:http://chinadenli.net/article26/pijsjg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供軟件開發(fā)、服務(wù)器托管、定制網(wǎng)站、App設(shè)計、網(wǎng)站設(shè)計、域名注冊
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)