Php 更改Laravel的名称';已在创建并更新了

Php 更改Laravel的名称';已在创建并更新了,php,mysql,laravel,laravel-4,Php,Mysql,Laravel,Laravel 4,我可以从以下位置映射Laravel的时间戳: 在创建到发布日期和发布日期\u gmt 在更新为修改后和修改后

我可以从以下位置映射Laravel的时间戳:

创建到
发布日期
发布日期\u gmt

更新为
修改后
修改后


我正在将Wordpress应用程序迁移到Laravel

我正在使用Laravel访问Wordpress数据库的副本。数据库的实时版本仍在使用中,因此我不想更改架构

Posts表有
post\u date
post\u gmt
post\u modified
post\u modified\u gmt
,但Laravel希望在
创建
,在
更新

是否有任何方法可以更改Laravel查找的列名


我希望Laravel更新已经存在的所有列的时间戳。

如果您查看
Eloquent
类的源代码

通过重写这些常量,您应该能够非常轻松地更改这些列名

<?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';

}

您可以尝试使用属性getter和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');
    }
}

我不知道这是否有效,但你可以试一试。当然,这可能是一个基础——你必须好好利用它。

不幸的是,被接受的答案可能会导致更新时间戳的问题

您最好覆盖模型上的常量:

const CREATED_AT = 'post_date';
const UPDATED_AT = 'post_modified';
然后方法
getCreatedAtColumn
getUpdatedAtColumn
将分别返回
post\u date
post\u modified
,但不会造成任何伤害


对于其他列,您需要使用类似@Oni建议的事件。

只需将其放入表模型文件中

 const CREATED_AT = 'your_custom_created_at_field_name';
 const UPDATED_AT = 'your_custom_updated_at_field_name';
为了避免混淆,我的模型是这样的

class diarymodule extends Model
{
    protected $table = 'diarymodule';
    const CREATED_AT = 'CreatedDate';
    const UPDATED_AT = 'UpdatedDate';
}

哦,忽略这一点,奥尼的更好!你能解释一下被接受的答案是如何引起问题的吗?我很感兴趣。雄辩的模型类在某些方法中指的是
static::CREATED_AT
static::UPDATED_AT
,也指@Oni覆盖的那2个方法。因此,对这些方法中的列进行硬编码可以在更新时间戳(例如,
updateTimestamps
方法)时对
created_在
updated_在
进行雄辩的搜索。当使用软删除时,
DELETED_AT
也是如此。嗯,这似乎是Laravel中的一个可能的错误(因为它应该使用方法而不是常量),对吗?如果覆盖常量,这是否只会影响设置它们的模型,或者覆盖它扩展的模型,因此会影响所有模型?当然,只会影响您设置它们的模型以及从中继承的所有模型,而不会影响父类-
Eloquent\model
。请检查我的答案,因为这会导致意外行为。我再次查看了源代码,正如deczo所说,当涉及到使用静态常量的其他方法时,我提供的代码将导致错误。我已经更新了代码示例以反映deczo的建议。这个答案与公认的答案有何不同?