![](/img/trans.png)
[英]Laravel 5.2: Mutators - How to combine two columns into one with mutators
[英]How to customize date mutators in Laravel?
我在我的数据库中创建了一些日期时间字段,正如Laravel文档中所述,我可以“自定义哪些字段会自动变异”。 然而,没有示例显示如何完成,也没有任何搜索结果。 我应该怎么做才能使某些字段自动变异?
例如,我在迁移中创建了一个名为“people”的表,其中一个字段定义如下:
class CreatePeopleTable extends Migration {
public function up(){
Schema::create("bookings",function($table){
...
$table->dateTime("birthday");
...
}
}
}
我在模型中为“人”定义了一个模型:
class People extends Eloquent{
//nothing here
}
如果我引用People实例的生日,它将是字符串,而不是DateTime
$one=People::find(1);
var_dump($one->birthday);
//String
日期变更器应该能够将它直接转换为Carbon对象,但是文档并没有说明应该如何实现它。
在您的People模型中,只需添加此数组:
protected $dates = array('birthday');
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);
}
根据此文档 ,您可以使用模型成员函数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
你是什么意思:自动变异?
如果你的意思是从数据库中检索后发生变异,请使用Accessors和Mutators(Laravel docs)。
将此添加到您的模型:
public function getDateAttribute( $date )
{
// modify $date as you want, example
// $date = new \Carbon\Carbon($date);
// $date->addDay()
// return (string)$date
}
正如Sasa Tokic所说,添加protected $dates = array('birthday');
对你的人物模型如下:
class People extends Eloquent{
protected $dates = array('birthday');
}
然后,您可以使用Carbon对此值执行巧妙的操作,如下所示:
$people->birthday->format('jS F Y')
PHP的date()
函数docs( http://uk3.php.net/manual/en/function.date.php )和Carbon的文档( https://github.com/briannesbitt/Carbon )将在这里提供帮助:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.