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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在Laravel 4中使用Eloquent Model增加列相关的知识,希望对你有一定的参考价值。

我不确定如何使用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');
答案

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

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

fix a few weeks ago之前,increment方法实际上落到了查询构建器,并且将在整个表上调用,这是不可取的。

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

另一答案

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

以上是关于如何在Laravel 4中使用Eloquent Model增加列的主要内容,如果未能解决你的问题,请参考以下文章

Payum - Laravel 4 的包。如何使用 Eloquent 而不是 FilesystemStorage 创建模型数据?

Laravel 4:如何使用 Eloquent ORM“排序”[重复]

如何使用 Laravel 4 Eloquent 连接列?

Laravel 4.2 Eloquent 获取特定用户和特定角色

Laravel 5.1 Eloquent isFillable() 单元测试中的差异

如何使用 eloquent 在 laravel 中编写多个连接