覆盖 created_at 值

Override created_at value

我正在尝试将日期插入创建时间,但没有任何效果

我尝试正常使用创建

$this->create([ 'product_id' => "$id", 'shop_name' => $shop,'created_at' => $date ]);

我尝试更改日期格式以匹配 laravel

$date = date('Y-m-d H:i:s',strtotime($id['created_at']));

我还尝试使用修改器每次更改值

public function setFirstNameAttribute($value)
{
    $this->attributes['created_at'] = $value;
}

如何在 created_at 中设置特定日期而不是默认日期?

您是否为您的模型设置了可填充或受保护的数组?

如果是这样,create 方法将跳过不可批量分配的字段。

如果你想自己填写,可以这样做:

$product = app(Product::class);
$product->timestamps = false; // disable timestamps for this creation

// set what you want to set
$product->product_id = $id;
$product->shop_name = $shop;
$product->created_at = $datetime; // <- datetime here
$product->save();

虽然,如果您查看代码 (vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasTimestamps.php),并且 created_at 字段是可填写的,如果它是在创建期间设置的,则不应设置其他值。 (请参阅那里的 isDirty 检查)


如果您不想以正常方式使用 created_at 和 updated_at,只需在您的模型中将时间戳设置为 false:

public $timestamps = false;

我认为您必须将模型中的时间戳设置为 false

timestamps = false;

这是一个很老的问题,但我想我要补充一点,你也可以使用 Model::unguard() 方法暂时禁用模型上的批量分配,这也可以让你为 created_at 以及受 MA 保护的任何其他内容。请注意,它还会级联到子关系,如下所示:

    $user = Auth::user();

    User::unguard();

    $user->drill_completions()->create([
        'day' => null,
        'sequence_completed_at' => Carbon::now(),
        'created_at' => Carbon::now()->subHours(32) // unguard has been set on the parent model, but here we are using it to enable setting created_at on the child relationship
    ]);

    User::reguard();

如上,您可以使用Model::reguard();再次重置。