3

I've created a few datetime fields in my database, and as is described in Laravel documentation, I can "customize which fields are automatically mutated". However there's no example showing how it can be done, nor is there any search result. What should I do to make certain fields auto mutate?

For example, I created a table called "people" in migration, one of the fields is defined as this:

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

And I defined a model for "people" in models:

class People extends Eloquent{
  //nothing here
}

If I refer to the birthday of a People instance, it'll be string, instead of DateTime

$one=People::find(1);
var_dump($one->birthday);
//String

The date mutator should be able to convert it directly to Carbon object, but the documentation doesn't say much about how it should be implemented.

4

4 回答 4

17

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

protected $dates = array('birthday');

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

/**
     * 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);
    }
于 2014-01-07T11:21:45.787 回答
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

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

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

因此,您可以将字段名称附加到此方法的返回值:

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

现在birthday,无论何时调用它,该字段都将作为 Carbon 实例返回:

$one = People::find(1);
var_dump($one->birthday);
//Carbon
于 2013-09-06T10:10:59.767 回答
3

你是什​​么意思:自动变异?

如果您的意思是从数据库检索后发生突变,请使用 Accessors 和 Mutators(Laravel 文档)。

将此添加到您的模型中:

public function getDateAttribute( $date )
{
     // modify $date as you want, example
     // $date = new \Carbon\Carbon($date);
     // $date->addDay()
     // return (string)$date
}
于 2013-08-23T12:19:45.260 回答
1

正如 Sasa Tokic 所说,protected $dates = array('birthday');像这样添加到您的人员模型中:

class People extends Eloquent{
    protected $dates = array('birthday');
}

然后,您可以使用 Carbon 对这个值做一些聪明的事情,如下所示:

$people->birthday->format('jS F Y')

PHP 的date()函数文档 ( http://uk3.php.net/manual/en/function.date.php ) 和 Carbon 的文档 ( https://github.com/briannesbitt/Carbon ) 将在这里提供帮助:

于 2014-03-02T16:42:01.733 回答