【问题标题】:Laravel updateOrCreate function does not update custom timestampLaravel updateOrCreate 函数不更新自定义时间戳
【发布时间】:2019-01-12 08:41:24
【问题描述】:

我正在使用 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();
});

【问题讨论】:

  • 你用的是哪个版本的 laravel?
  • 我的 Laravel 是 v5.7

标签: laravel laravel-5 eloquent


【解决方案1】:

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'];

【讨论】:

    【解决方案2】:

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

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

    它对你有用吗?

    【讨论】:

    • 这是什么意思? protected $dates = [ 'last_scan', ]; 该字段已经存在并且正在更新中!
    • 这基本上意味着它应该被变异为一个日期。你试过我的建议还是不行?
    • 我不是提问者 :)
    • 这不是问题,但请给我另一个观点。我再次检查了模型,发现它与受保护的 $fillable 数组有关。除了“last_scan”之外,我有所有字段,这就是他是唯一没有更新的字段的原因。 $dates 帮助我解决了与此模型完全无关的其他问题:) 谢谢
    猜你喜欢
    • 2015-02-20
    • 1970-01-01
    • 2019-08-05
    • 1970-01-01
    • 2013-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多