2013-05-16 69 views
3

我不確定如何使用Laravel 4中的雄辯模型增加列中的值? 這是我現在有的,我不知道這是多麼正確。如何在Laravel 4中使用雄辯模型增加列

$visitor = Visitor::where('token','=','sometoken')->first(); 
if(isset($visitor)){ 
    $visitor->increment('totalvisits'); 
}else{ 
    Visitor::create(array(
    'token'=>'sometoken', 
    'totalvisits'=>0 
    )); 
} 

隨着查詢生成器,我們可以用做

DB::table('visitors')->increment('totalvisits'); 
+0

你的代碼在我的最後工作正常,還有什麼比你發佈的更多嗎? – ARW

+0

增量方法被調用後,我應該調用save方法嗎? –

+3

您不需要使用'increment'方法,因爲它確實打算用於以後不會保存的查詢。你也可以去$ visitor-> totalvisits = $ visitor-> totalvisits + 1; $ visitor->保存(); – ARW

回答

21

貌似之後我張貼工作的所有代碼

$visitor = Visitor::where('token','=','sometoken')->first(); 
if(isset($visitor)){ 
    $visitor->increment('totalvisits'); 
}else{ 
    Visitor::create(array(
    'token'=>'sometoken', 
    'totalvisits'=>0 
    )); 
} 
5

此前有fix a few weeks agoincrement方法實際上是通過對查詢生成器下降,並會在整個表,這是不可取叫。

現在在模型實例上調用incrementdecrement將僅在該模型實例上執行操作。

+0

謝謝Jason,我不確定如何使用增量方法和雄辯代碼中提到的模型和我的代碼運行良好。感謝你的幫助。 –

1

Laravel 5現擁有原子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); 
} 

其基本上一樣:

Customer::query() 
->where('id', $customer_id) 
->update([ 
'loyalty_points' => DB::raw('loyalty_points + 1') 
]); 

下面是老回答Laravel 4,內置增量是單獨選擇,然後更新wh當然ICH導致與多個用戶的錯誤:

如果你想確保更新準確地計算你的訪問者是原子,然後嘗試把這個在您的訪客模式:

public function incrementTotalVisits(){ 
    // increment regardless of the current value in this model. 
    $this->where('id', $this->id)->update(['totalVisits' => DB::raw('last_insert_id(totalVisits + 1)')]); 

    //update this model incase we would like to use it. 
    $this->totalVisits = DB::getPdo()->lastInsertId(); 

    //remove from dirty list to prevent any saves overwriting the newer database value. 
    $this->syncOriginalAttribute('totalVisits'); 

    //return it because why not 
    return $this->totalVisits; 
} 

我使用它適用於變更標籤系統,但也可能適合您的需求。

有沒有人知道要替換「$ this-> where('id',$ this-> id)」,因爲自從處理$ this Visitor之後,它應該是多餘的。

+0

我留下了對您的其他評論的回覆,但似乎我使用的Laravel版本(5.3)實現了原子「增量」方法。查看[照明查詢構建器文檔](https://github.com/illuminate/database/blob/master/Query/Builder.php),'increment'功能在2177行。 –

+0

請參閱https:// laravel .com/docs/5.6/queries#遞增和遞減 – mike

+0

@MattK好點我已更新我的答案 – malhal