gpt4 book ai didi

laravel-5 - 扩展 Laravel 的基础模型

转载 作者:行者123 更新时间:2023-12-05 02:19:55 26 4
gpt4 key购买 nike

在 Laravel 中,所有模型都扩展了基础模型。

laravel eloquent 模型有一个名为 $dates 的 protected 数组属性。添加到此数组的每个日期都会自动转换为 Carbon 实例。

我想用类似的功能扩展基本模型。例如,使用 protected $times 属性。所有时间属性都将转换为 Carbon 实例

你会怎么做?

提前致谢。

最佳答案

无论您想做什么,这都很容易。基本的 PHP 知识。

如果你想添加一些其他字段转换为Carbon实例,只需将它们添加到$dates数组

如果你想添加一些新参数,只需扩展 laravel 的模型,如下所示

<?php
namespace App;

class MyModel extends \Illuminate\Database\Eloquent\Model
{

protected $awesomness = [];

/**
* override method
*
*/
public function getAttributeValue($key)
{
$value = $this->getAttributeFromArray($key);

// If the attribute has a get mutator, we will call that then return what
// it returns as the value, which is useful for transforming values on
// retrieval from the model to a form that is more useful for usage.
if ($this->hasGetMutator($key))
{
return $this->mutateAttribute($key, $value);
}

// If the attribute exists within the cast array, we will convert it to
// an appropriate native PHP type dependant upon the associated value
// given with the key in the pair. Dayle made this comment line up.
if ($this->hasCast($key))
{
return $this->castAttribute($key, $value);
}

// If the attribute is listed as a date, we will convert it to a DateTime
// instance on retrieval, which makes it quite convenient to work with
// date fields without having to create a mutator for each property.
if (in_array($key, $this->getDates()) && !is_null($value))
{
return $this->asDateTime($value);
}

//
//
// that's the important part of our modification
//
//
if (in_array($key, $this->awesomness) && !is_null($value))
{
return $this->doAwesomness($value);
}

return $value;
}

public function doAwesomness($value)
{
//do whatever you want here
return $value;
}

}

然后你所有的模型只需要扩展 \App\MyModel 类而不是 \Illuminate\Database\Eloquent\Model

关于laravel-5 - 扩展 Laravel 的基础模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40768518/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com