Laravel Database Migrations中的 timestamps 與 nullableTimestamps

Posted by Y Cheung on Tue, Feb 25, 2020

才知道Laravel Database Migrations 中的 timestampsnullableTimestamps 在版本5.5之後數據庫中建立的是相同類型和屬性的column!!!好坑啊!!!

原文件(vendor/laravel/framework/src/Illuminate/Database/Schema/Blueprint.php)中指出:

 1    /**
 2     * Add nullable creation and update timestamps to the table.
 3     *
 4     * @param  int  $precision
 5     * @return void
 6     */
 7    public function timestamps($precision = 0)
 8    {
 9        $this->timestamp('created_at', $precision)->nullable();
10
11        $this->timestamp('updated_at', $precision)->nullable();
12    }
13
14    /**
15     * Add nullable creation and update timestamps to the table.
16     *
17     * Alias for self::timestamps().
18     *
19     * @param  int  $precision
20     * @return void
21     */
22    public function nullableTimestamps($precision = 0)
23    {
24        $this->timestamps($precision);
25    }

文檔也變成了:

Command Description
$table->nullableTimestamps(); Alias of timestamps()method.
$table->timestamps(); Adds nullable created_at and updated_at TIMESTAMP equivalent columns.

處理這倆個field的默認值是在Eloquent中,所以如果你有table不是對應Eloquent ORM的話,要記得自己手動插入值,或者從數據庫層給這倆個字段增加一個默認值。

PS. MYSQL 5.7版本timestamp類型的字段設置默認值的時候會遇到報錯,在這個issue中有提及( https://github.com/cakephp/phinx/issues/1531 ),目前還沒找到這個問題的解決方案,歡迎大家提供。