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

问题描述 投票:2回答:4

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

我想改变列定义以获得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 |
+----+---------------------+---------------------+----------------+------------+
eloquent laravel-5.1
4个回答
3
投票

您需要使用Eloquent Entity来创建对象。

请记住,Eloquent将根据类名搜索数据库名称。该类必须是单一形式,但雄辩将搜索它的复数版本。

如果您的数据库调用与类不同,则必须添加属性$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列将自动更新。


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值。

如果传递任何值,则将使用传递的值更新列。


0
投票

事实证明,如果我创建一个我的数据库表的Eloquent模型,那么当我使用该类时它将自动填写时间戳。 + RTFM :)


0
投票

我有一次经历,我错过了将created_at和updated_at放在模型上。

见下面的例子:

protected $fillable = [
        'id',
        'name',
        'username',
        'password',
        'created_at',
        'updated_at'
];
© www.soinside.com 2019 - 2024. All rights reserved.