如何在Laravel 4中使用Eloquent Model增加列

问题描述 投票:3回答:3

我不确定如何使用Laravel 4中的Eloquent Model增加列中的值?这就是我目前所拥有的,我不确定这是多么正确。

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

使用Query Builder,我们可以使用它

DB::table('visitors')->increment('totalvisits');
laravel laravel-4 eloquent
3个回答
22
投票

看起来我发布的代码毕竟有效

$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 ago之前,increment方法实际上落到了查询构建器,并且将在整个表上调用,这是不可取的。

现在,在模型实例上调用incrementdecrement将仅对该模型实例执行操作。


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的旧答案,其中内置增量是一个单独的选择,然后更新当然导致多个用户的错误:

如果您希望通过确保更新是原子的来准确计算访问者数,那么请尝试将其放入访问者模型中:

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以来它应该是多余的。

© www.soinside.com 2019 - 2024. All rights reserved.