如何在Laravel中自定义日期变更器?

Xun*_*ang 3 php laravel laravel-4

我在我的数据库中创建了一些日期时间字段,正如Laravel文档中所述,我可以"自定义哪些字段会自动变异".然而,没有示例显示如何完成,也没有任何搜索结果.我应该怎么做才能使某些字段自动变异?

例如,我在迁移中创建了一个名为"people"的表,其中一个字段定义如下:

class CreatePeopleTable extends Migration {
  public function up(){
    Schema::create("bookings",function($table){
      ...
      $table->dateTime("birthday");
      ...
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我在模型中为"人"定义了一个模型:

class People extends Eloquent{
  //nothing here
}
Run Code Online (Sandbox Code Playgroud)

如果我引用People实例的生日,它将是字符串,而不是DateTime

$one=People::find(1);
var_dump($one->birthday);
//String
Run Code Online (Sandbox Code Playgroud)

日期变更器应该能够将它直接转换为Carbon对象,但是文档并没有说明应该如何实现它.

小智 17

在您的People模型中,只需添加此数组:

protected $dates = array('birthday');
Run Code Online (Sandbox Code Playgroud)

Laravel的Model.php internaly将您的字段与默认字段合并,如下所示:

/**
     * Get the attributes that should be converted to dates.
     *
     * @return array
     */
    public function getDates()
    {
        $defaults = array(static::CREATED_AT, static::UPDATED_AT, static::DELETED_AT);

        return array_merge($this->dates, $defaults);
    }
Run Code Online (Sandbox Code Playgroud)


Xun*_*ang 5

根据此文档,您可以使用模型成员函数getDates()来自定义哪些文件自动变异,因此以下示例将返回Carbon实例而不是String:

$one = People::find(1);
var_dump($one->created_at);//created_at is a field mutated by default
//Carbon, which is a subclass of Datetime
Run Code Online (Sandbox Code Playgroud)

但它没有明确说明如何添加自己的字段.我发现该getDates()方法返回一个字符串数组:

$one = People::find(1);
echo $one->getDates();
//["created_at","modified_at"]
Run Code Online (Sandbox Code Playgroud)

那么你可以做的是将字段名称附加到此方法的返回值:

class People extends Eloquent{
    public function getDates(){
        $res=parent::getDates();
        array_push($res,"birthday");
        return $res;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,birthday每当您调用它时,字段将作为Carbon实例返回:

$one = People::find(1);
var_dump($one->birthday);
//Carbon
Run Code Online (Sandbox Code Playgroud)