如何在 Laravel 中自定义日期修改器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18401771/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:19:20  来源:igfitidea点击:

How to customize date mutators in Laravel?

phplaravellaravel-4

提问by Xun Yang

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?

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

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

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

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

如果我指的是 People 实例的生日,它将是字符串,而不是 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.

date mutator 应该能够将它直接转换为 Carbon 对象,但是文档并没有说明它应该如何实现。

回答by Sasa Tokic

In your People model just add this array:

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

protected $dates = array('birthday');

Laravel's Model.php internaly merges your fields with the default ones like this:

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);
    }

回答by Xun Yang

According to this doc, you can use model member function getDates()to customize which fileds are automatically mutated, so the following example will return Carbon instance instead of String:

根据这个doc,您可以使用模型成员函数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

But it doesn't say clearly how to add your own fields. I found out that the getDates()method returns an array of strings:

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

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

So what you can do is appending field names to the return value of this method:

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

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

Now birthdayfield will be returned as a Carbon instance whenever you call it:

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

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

回答by Blue Genie

What do you mean by: automatically mutated?

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

If you mean mutated after being retrieved from DB use Accessors and Mutators (Laravel docs).

如果您的意思是在从数据库中检索后发生变异,请使用访问器和变异器(Laravel 文档)。

Add this to your model:

将此添加到您的模型中:

public function getDateAttribute( $date )
{
     // modify $date as you want, example
     // $date = new \Carbon\Carbon($date);
     // $date->addDay()
     // return (string)$date
}

回答by atwright147

As Sasa Tokic says, add protected $dates = array('birthday');to your People model like so:

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

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

You can then use Carbon to do clever things to this value, like so:

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

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

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

PHP's date()function docs (http://uk3.php.net/manual/en/function.date.php) and Carbon's docs (https://github.com/briannesbitt/Carbon) will help here:

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