Laravel 7时间戳迁移在导入CSV Excel文件时始终返回0000-00-00 00:00:00

问题描述

搜索了所有相关文章,但没有解决方案。当我意识到时间戳不正确时,我正在为Laravel设置站点地图。因此,这对SEO不利。

我在MysqL数据库的created_at和Updated_at字段中总是有0。

我不确定这是Laravel,sql还是Excel问题。

我做什么:

  • 在本地主机的laravel中迁移我的表 $table->timestamps(); 也尝试过了,但没有尝试
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->useCurrent();
$timestamps = false;
$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));

也许还有另一种方法可以正确地做到这一点?

解决方法

如果您使用的是 maatwebsite/excel,并且如果您同样通过迁移创建了时间戳,那么模型将自动插入时间戳。

    $table->timestamps();

注意:确保您的表列 created_at 不存在于模型的可填充数组中,并且您没有使用文档中提到的 WithUpserts 方法。 见:https://docs.laravel-excel.com/3.1/imports/model.html

protected $fillable = [
         'users_id','name','created_at' //it should not be here
]

另一种使用碳的方法

您必须通过使用碳来添加时间戳。

首先在模型的可填充数组中添加 created_at

 protected $fillable = [
          
             'name','created_at' //must be present
    ]  

然后您必须使用 carbon,转到您的导入文件夹并在您的导入文件中,进行以下标有注释的更改。

 <?php

namespace App\Imports;
use Carbon\Carbon; //add this line of code

use App\User;
use Illuminate\Support\Facades\Hash;
use Maatwebsite\Excel\Concerns\ToModel;

class UsersImport implements ToModel
{
    /**
     * @param array $row
     *
     * @return User|null
     */
    public function model(array $row)
    {
        return new User([
           
           'created_at'=> now(),//add this line of code
           'name'     => $row[0],]);
    }
}

注意:它也适用于 upserts,在 upserts 中,maatwebsite 无法添加时间戳,它将为 null,但使用上述方法可以存储时间戳,您可以对 updated_at 使用相同的方法。