在 Eloquent 中自动生成和自动更新时间戳

Auto-generate and auto-update timestamps in Eloquent

我是 Laravel 的新手,我正在处理我的数据库迁移。对于一个 table,我在 table 定义中包含了 $table->timestamps() 快捷方式。令我沮丧的是,我发现在我播种 table 之后,created_atupdated_at 的值都是 0000-00-00 00:00:00

我正在考虑将列定义更改为 DEFAULT CURRENT_TIMESTAMPDEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,但后来我想知道为什么 Eloquent 还没有这样做。我想这一定是出于一个很好的理由 (tm)。我想这是为了与支持的不同数据库兼容?

如果我继续更改列定义,我是否将自己锁定在 MySQL 解决方案中?我 真的 不想记住更新每个 CREATEINSERT 的时间戳......有没有办法使用 Eloquent成语?

相关代码:

// migration method
public function up()
{
    Schema::create('categories', function (Blueprint $table) {
        $table->increments('id');
        $table->timestamps();
        $table->string('category');
        $table->integer('sort_order')->unsigned();
        $table->index('sort_order');
    });
}

// seeder method
public function run()
{
    $data = [
          'Category 1'
        , 'Category 2'
    ];

    $sort = 0;

    foreach ( $data as $category ) {
        DB::table('categories')->insert([
            'category' => $category,
            'sort_order' => $sort++,
        ]);
    }
}

// database query
mysql> select * FROM categories;
+----+---------------------+---------------------+----------------+------------+
| id | created_at          | updated_at          | category       | sort_order |
+----+---------------------+---------------------+----------------+------------+
|  1 | 0000-00-00 00:00:00 | 0000-00-00 00:00:00 | Category 1     |          0 |
|  2 | 0000-00-00 00:00:00 | 0000-00-00 00:00:00 | Category 2     |          1 |
+----+---------------------+---------------------+----------------+------------+

如果您想通过 mysql db 自己实现它,那么您的列 属性 应该如下所示-

ALTER TABLE mytable 
MODIFY COLUMN created TIMESTAMP DEFAULT CURRENT_TIMESTAMP, 
MODIFY COLUMN modified TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;

现在不要在您的数据插入和修改代码中包含这两列,然后 mysql 会自动将这些列填充为 current_timestamp 值。

如果您传递任何值,则列将更新为传递的值。

事实证明,如果我为我的数据库 table 创建了一个 Eloquent 模型,那么当我使用 class 时它会自动填充时间戳。 +1 用于 RTFM :)

您需要使用 Eloquent 实体来创建您的对象。

请记住 Eloquent 将根据 class 名称搜索数据库名称。 class 必须是单一形式,但 eloquent 将搜索它的复数形式。

如果您的数据库与 class 的名称不同,您必须添加 属性 $table.

<?php 

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model 
{
     protected $table = 'categories'; // not neccessary in this case

}

创建新行

$category = new CategoryEntity();
$category->category = 'your category';
$category->sort_order = 'your sort order';
$category->save();

更新您的实体

$category = CategoryEntity::find($your_category_id);
$category->category = 'your category';
$category->sort_order = 'your sort order';
$category->update();

当您像这样使用时,列 created_at 和 updated_at 将自动更新。

我有一个经验,我只是错过了把 created_at & updated_at 放在型号。

参见下面的示例:

protected $fillable = [
        'id',
        'name',
        'username',
        'password',
        'created_at',
        'updated_at'
];