在Laravel 5中,时间戳(updated_at,created_at)为空。

16 浏览
0 Comments

在Laravel 5中,时间戳(updated_at,created_at)为空。

我在Laravel 5中遇到了updated_atcreated_at字段的问题。

这是我的迁移代码:

Schema::create('lots', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('lot');
    $table->integer('is_active');
    $table->timestamps();
});

但是当我向这个表中插入数据时,updated_atcreated_at字段是空的。如何使它们自动填充当前时间戳?

我像这样插入数据:

\DB::table('admin_lots')->insert([
    'lot' => $request->cycle_lot,
    'is_active' => '1',
]);

谢谢。

0
0 Comments

在Laravel 5中,如果你发现Timestamps(updated_at,created_at)的值为null,那么这个问题的出现原因可能是在你的模型中设置了public $timestamps = false;。解决方法是删除这一行代码。

如果这一行代码出现在父类中,你需要添加public $timestamps = true;来启用Timestamps。

0
0 Comments

Timestamps (updated_at, created_at) are null in Laravel 5

在Laravel 5中,如果你在插入数据时没有使用Eloquent,那么会出现Timestamps(updated_at,created_at)为空的问题。在这种情况下,你应该手动添加timestamps。

如果你不想这样做,但仍然需要填充timestamps,可以使用以下方法:

$table->timestamp('created_at')->default(\DB::raw('CURRENT_TIMESTAMP'));
$table->timestamp('updated_at')->default(\DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));

根据你更新后的代码,这里有另一种解决方法:

\DB::table('admin_lots')->insert([
    'lot' => $request->cycle_lot,
    'is_active' => '1',
    'created_at' => \Carbon\Carbon::now()->toDateTimeString(),
    'updated_at' => \Carbon\Carbon::now()->toDateTimeString()
]);

根据你的代码更新了如何插入数据。谢谢你的答案,我现在会尝试它。

根据你的代码,添加了另一种手动创建timestamps的解决方法。

老实说,这似乎是一个使用Eloquent的案例。在这种情况下,直接使用数据库插入是一个不好的做法。

谢谢!这两种解决方法都适用于我,但第一种更好。非常感谢!

在OP没有提供任何代码的情况下,我发表了第一种解决方法,并且我写了这是一种“hack”。

确实。但是这种hack肯定会给其他人带来麻烦。

0
0 Comments

在Laravel 5中,如果想要在数据库表中的时间戳字段(updated_at和created_at)自动更新时间,就需要使用create方法而不是insert方法。

create方法会自动为created_atupdated_at字段添加时间戳:

// 正确的方法:
User::create(array(
    'name' => 'John'
));

相反地,insert方法绕过Eloquent(而是使用查询构建器),并不会更新updated_atcreated_at列!

// 错误的方法:
User::insert([
    'name' => '[[ test name ]]',
]);
dd(
    User::where(['name' => '[[ test name ]]'])->first()->create_date
);

如上图所示,insert方法插入的数据的时间戳字段将会是空值。

如果需要进行多次插入操作,可以考虑使用insertGetId方法,该方法会返回插入数据的ID值。

希望对你有所帮助!

0