Laravel - 更新时禁用更新时间

问题描述 投票:14回答:5

在laravel 5上使用查询构建器获取更新问题。我已尝试禁用updated_at但仍然失败。

这是我的代码:

    $query = StockLog::where('stock_id', $id)->whereBetween('created_at', $from, $to])->update(['batch_id' => $max + 1]);

我尝试了两种方法:第一种在我的模型中设置:

public function setUpdatedAtAttribute($value)
{
    /*do nothing*/
}

第二个:

$stocklog = new StockLog;
$stocklog->timestamps = false;

$query = $stocklog::where('stock_id', $id)->whereBetween('created_at', [$from, $to])->update([
        'batch_id' => $max + 1]);

他们俩都失败了。无论如何要禁用updated_at?

提前致谢

php laravel laravel-4 laravel-5
5个回答
25
投票

默认情况下,Eloquent将自动维护数据库表上的created_at和updated_at列。只需将这些时间戳列添加到您的表中,Eloquent将负责其余部分。

我真的不建议删除它们。但是如果你想使用以下方式。

将以下内容添加到您的模型中:

public $timestamps = false;

这将禁用时间戳。

编辑:看起来你想保留created_at字段,你可以覆盖模型中的getUpdatedAtColumn

使用以下代码:

public function getUpdatedAtColumn() {
    return null;
}

8
投票

在您的模型中,添加此方法:

/**
 * @param  mixed  $value
 * @return $this
 */
public function setUpdatedAt($value)
{
    return $this;
}

更新:在Laravel 5.5中:

试着在你的模型中使用它:

const CREATED_AT = null;
const UPDATED_AT = null;

6
投票

接受的答案对我不起作用,但是让我朝着这个解决方案的正确方向前进:

class Whatever extends Model {
    //...
    const UPDATED_AT=NULL;
    //...

Laravel 5.3


2
投票

如果您想永久关闭它,可以使用以下。

在模型中添加以下内容......

public $timestamps = false;

如果你想继续使用created_at,那么添加以下内容。

    static::creating( function ($model) {
        $model->setCreatedAt($model->freshTimestamp());
    });

或使用以下方式......

/**
 * Set the value of the "updated at" attribute.
 *
 * @param  mixed  $value
 * @return void
 */
public function setUpdatedAt($value)
{
    $this->{static::UPDATED_AT} = $value;
}

0
投票

在这种情况下,最好使用查询生成器而不是Eloquent,因为查询生成器不会隐含地编辑时间戳字段。使用Query Builder将具有仅针对相关更新操作而无需更改所有模型的优势。

在一行中你可以做到:

$query = \DB::table('stocklogs')->where('stock_id', $id)->whereBetween('created_at', [$from, $to])->update(['batch_id' => $max + 1]);
© www.soinside.com 2019 - 2024. All rights reserved.