【问题标题】:Updated_at still being updated even with timestamps to falseUpdated_at 仍在更新,即使时间戳为 false
【发布时间】:2021-11-05 15:39:27
【问题描述】:

我正在将我的数据库从 prestashop 迁移到 laravel,所以我想保留相同的数据(包括创建和更新日期)。但是,即使将时间戳设置为 false,我的 store 模型中的 updated_at 列也会不断更新。

    $data = request()->validate([
        'name' => 'required|string',
        'iban' => 'sometimes|required|iban',
        'contact' => 'required|array',
        'contact.first_name' => 'required|string',
        'contact.last_name' => 'required|string',
        'contact.email' => 'required|string|unique:users,email',
        'contact.phone' => 'nullable|string',
        'billing_address' => 'sometimes|required|array',
        'billing_address.street_address' => 'sometimes|required|string',
        'billing_address.complement' => 'nullable|string',
        'billing_address.postal_code' => 'sometimes|required|string',
        'billing_address.city' => 'sometimes|required|string',
        'billing_address.country' => 'sometimes|required|string',
        'billing_address.region' => 'nullable|string',
        'created_at' => 'required|date',
        'updated_at' => 'required|date',
    ]);
    $store = app('store')->create(array_merge($data, [
        'status' => Store::STATUS_DRAFT,
        'type' => 'default',
        'company' => '',
        'tos_accepted_at' => null,
    ]));
    if (isset($data['billing_address'])) {
        $billing_address = $store->addresses()->create($data['billing_address']);
        $store->billing_address()->associate($billing_address);
    }
    $contact = $store->users()->create(array_merge($data['contact'], [
        'role' => 'user',
        'locale' => 'fr',
        'country' => optional($store->billing_address)->country ?? 'fr',
        'temporary_password' => 1,
        'password' => '',
    ]));
    $store->contact()->associate($contact);
    $store->timestamps = false;
    $store->save();

【问题讨论】:

  • 您通过在验证'created_at' => 'required|date', 'updated_at' => 'required|date', 中明确填充created_atupdated_at,删除它,它应该可以工作。
  • @TimLewis 它不起作用,甚至我的 created_at 列现在也更新了
  • @TimLewis OP 期望覆盖具有 prestashop 值的update_at。但 Laravel 不在乎。
  • @WahyuKristianto 精确
  • 哦,对不起,这更有意义。因此,您希望通过$data(来自prestashop 值)设置created_atupdated_at,但是然后(例如)将updated_at 设置为今天的日期?我想知道$store->timestamps = false; 是否在已经填充值时表现不佳????或者,您可以放弃使用模型,而是使用DB::table('stores')->insert(...),当使用DB::table() 时,它没有模型时间戳的概念,只会从$data 填充

标签: php laravel migration


【解决方案1】:

好的,我正在尝试欺骗 Laravel。

$store = app('store')->create(array_merge($data, [
    'status' => Store::STATUS_DRAFT,
    'type' => 'default',
    'company' => '',
    'tos_accepted_at' => null,
]));

$store->setCreatedAt($data['created_at']);
$store->setUpdatedAt($data['updated_at']);

$store->save();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-30
    • 2014-07-18
    • 1970-01-01
    • 1970-01-01
    • 2019-05-06
    • 1970-01-01
    • 2016-08-28
    • 2013-10-05
    相关资源
    最近更新 更多