mardi 22 septembre 2015

auto-generate and auto-update timestamps in eloquent

I am new to Laravel and I am working on my database migrations. For one table, I've included the $table->timestamps(); shortcut in my table definition. To my dismay, I found that after I seeded the table, the values were 0000-00-00 00:00:00 for both created_at and updated_at.

I was thinking to change the column definitions to have DEFAULT CURRENT_TIMESTAMP and DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, but then I wondered why Eloquent wasn't already doing this. I suppose it's for compatibility with the different databases supported?

If I go ahead and change the column definitions, am I locking myself into a MySQL solution? I really don't want to have to remember to update the timestamps on every CREATE and INSERT ...

Relevant code:

// 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 |
+----+---------------------+---------------------+----------------+------------+



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire