2013-05-16 67 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