Laravel updateOrCreate函数不会更新自定义时间戳

时间:2019-01-12 08:41:25

标签: laravel laravel-5 eloquent

我正在使用updateOrCreate函数创建新行或基于给定值更新存在。但是,当我尝试更新定义为时间戳的值(而不是默认的“ created_at”或“ updated_at”)时,它不会更新该值。

仅当我使用updateOrCreate函数并且仅要更新的唯一字段是时间戳字段时,才会发生此问题。 (对于我来说,是“ last_scan”)。 例如,当我将“状态”更改为0时,数据库中所有更新的值都包含“ last_scan”字段。

我想验证每次运行此函数时,last_scan是否已更新为函数运行时是否有数据要更新。

$categoryEntity = CategoryEntity::updateOrCreate(
    [
        'store_id'  => $this->store_id,
        'remote_id' => $collection->id
    ],
    [
        'remote_parent_id'  => 0,
        'name'              => $collection->title,
        'status'            => 1,
        'last_scan'         => Carbon::now()
    ]
);

我尝试替换更新并使用常规更新方法创建,如下所示,它运行良好:

$categoryEntity->last_scan = Carbon::now();
$categoryEntity->save();

我的迁移文件如下:

Schema::create('categories_entities', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('store_id');
            $table->integer('remote_id');
            $table->integer('remote_parent_id');
            $table->string('name');
            $table->integer('status');
            $table->timestamp('last_scan');
            $table->timestamps();
});

2 个答案:

答案 0 :(得分:1)

在CategoryEntity模型文件中,添加以下属性:

/**
 * The attributes that should be mutated to dates.
 *
 * @var array
 */
protected $dates = [
    'last_scan',
];

它对您有用吗?

答案 1 :(得分:0)

TL; DR

模型中的“受保护的$ fillable”属性不包含“ last_scan”字段。

深入了解

稍作搜索后,我注意到createOrUpdate方法使用了批量更新功能。 $ fillable属性必须包含我们要提供的用于批量更改它们的所有字段。

我再次查看模型,发现其中受保护的$ fillable属性包含除“ last_scan”以外的所有字段。

原是:

protected $fillable = ['store_id', 'remote_id', 'remote_parent_id', 'name', 'status'];

现在:

protected $fillable = ['store_id', 'remote_id', 'remote_parent_id', 'name', 'status', 'last_scan'];