2013-10-21 144 views
1

我正在使用Laravel的迁移来创建一些数据库表,我想知道是否有可能创建DATETIME列而不是TIMESTAMP。我使用的代码如下:在Laravel中更改created_at和updated_at的格式4

$table->increments('id'); 
$table->string('name', 255); 
$table->bigInteger('size'); 
$table->dateTime('downloaded_at'); 
$table->timestamps(); 

我知道我可以更改日期,回来在我的模型使用属性的格式,但是我想他们如果可能的话要DATETIME在我的数据库。

+0

你为什么喜欢'DATETIME'?我通常更喜欢'TIMESTAMP',因为它是时区感知的。 – eggyal

+0

@eggyal,你已经倒退了; 'DATETIME'包含时区信息,'TIMESTAMP'始终保存为UTC。 –

+0

@BillKarwin:据我所知,'DATETIME'根本不存储任何时区信息?通过说'TIMESTAMP'是'时区意识',我的意思是它在会话'time_zone'(在客户端)和UTC(用于存储)之间转换。 – eggyal

回答

1

我在源代码中做了一些挖掘,并且时间戳的类型是硬编码的,因此您不能仅将其重新配置为DateTime

我认为更好的办法是为你创建自己的列(不使用时间戳()) ,然后在你的模型,你可以这样做:

public class User extends Eloquent 
{ 
     public function save() 
     { 
      $this->attributes['created_at'] = new DateTime; 
      return parent::save(); 
     } 
} 

另一种方法是使用ModelObservers

class UserObserver { 

    public function saving($model) 
    { 
     // 
    } 
} 

User::observe(new UserObserver); 

,你也可以尝试可能重写Blueprint类的timestamp()功能,但没有保证,这不会弄乱Laravel代码中的其他地方,BEC澳洲英语它采用碳处理日期等..

class MyBlueprint extends Blueprint 
{ 
     public function timestamp($column) 
     { 
       return $this->addColumn('dateTime', $column); 
     } 
} 

然后定义你的表结构时的迁移使用MyBlueprint:

Schema::create('users', function(MyBlueprint $table) { 
    // code 
    $this->timestamps(); 
} 
相关问题