2014-06-25 169 views
23

我可以從地圖Laravel的時間戳:更改名稱和的updated_at

created_atpost_datepost_date_gmt

updated_atpost_modifiedpost_modified_gmt


我正在將一個Wordpress應用程序遷移到Laravel。

我正在使用Laravel訪問Wordpress數據庫的副本。數據庫的實時版本仍在使用中,因此我不想更改架構。

的帖子表有post_datepost_date_gmtpost_modifiedpost_modified_gmt,但Laravel期待created_atupdated_at

無論如何改變Laravel尋找的列名?

我想讓Laravel更新已經存在的所有列的時間戳。

回答

40

不幸的是,接受的答案可能會導致更新時間戳的問題。

您在模型上最好覆蓋consts:

const CREATED_AT = 'post_date'; 
const UPDATED_AT = 'post_modified'; 

然後方法getCreatedAtColumngetUpdatedAtColumn將分別返回post_datepost_modified,但不會做任何傷害。

對於其他需要使用@Oni建議的事件列。

+0

您能否解釋接受的答案可能會導致問題?我很好奇。 – alexrussell

+0

Eloquent Model類在某些方法中引用了'static :: CREATED_AT'和'static :: UPDATED_AT',在@Oni覆蓋的特定2中也是如此。因此,在更新時間戳(例如'updateTimestamps'方法)時,對這些方法中的列進行硬編碼將使Eloquent無論如何搜索'created_at'和'updated_at'。使用軟刪除時,對於'DELETED_AT'也是如此。 –

+0

嗯,這似乎是一個可能的錯誤在Laravel(因爲它應該使用的方法不是常量),對不對? – alexrussell

19

如果你看看Eloquent

https://github.com/illuminate/database/blob/4.2/Eloquent/Model.php#L223-L235

的源時,您應該能夠通過重寫這些常量很容易地改變這些列名。

<?php 

class YourModel extends Eloquent { 

    /** 
    * The name of the "created at" column. 
    * 
    * @var string 
    */ 
    const CREATED_AT = 'post_date'; 

    /** 
    * The name of the "updated at" column. 
    * 
    * @var string 
    */ 
    const UPDATED_AT = 'post_modified'; 

} 

對於_gmt版本的時間戳,您可能想看看events。這是一個良好的開端

http://driesvints.com/blog/using-laravel-4-model-events

+0

檢查我的答案,因爲這將導致意想不到的行爲。 –

+0

我再次查看了源代碼,正如deczo所說的那樣,我提供的代碼在使用靜態常量的其他方法時會導致錯誤。我已經更新了代碼示例以反映deczo的建議。 – Oni

0

你可以嘗試使用屬性getter和干將:

class Post extends Eloquent 
{ 
    public function getCreatedAtAttribute() 
    { 
     return $this->attributes['post_date']; 
    } 

    public function setCreatedAtAttribute($value) 
    { 
     $this->attributes['post_date'] = $value; 

     // this may not work, depends if it's a Carbon instance, and may also break the above - you may have to clone the instance 
     $this->attributes['post_date_gmt'] = $value->setTimezone('UTC'); 
    } 
} 

我不知道這是否會工作,但你可以給它一個去。當然,也許有一個基礎 - 你必須玩弄它。

+0

哦,忽略這個,奧尼的好多了! – alexrussell