2014-06-25 166 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