Larvel使用snake_case作为表列名。如何以下面的getter工作方式覆盖这个假设?
public function getFooBarAttribute()
{
return json_decode($this->attributes['fooBar'], true);
}
答案 0 :(得分:7)
I need to first caveat this answer with the following: I haven't tested this code; secondly I have never had a requirement to use this.
With that said, there is a static property available on eloquent models:
/**
* Indicates whether attributes are snake cased on arrays.
*
* @var bool
*/
public static $snakeAttributes = true;
By switching this to false, you turn off snake casing of attribute names AND relationship names on the model. This should have the desired outcome you are looking for.
If you're interested the source code的href值有一个方法cacheMutatedAttributes
,它在属性中运行正则表达式,以检查是否存在任何突变,如果匹配则通过以下代码段运行。
if (static::$snakeAttributes) {
$match = Str::snake($match);
}
由于这是一个静态属性,您可以通过更改模型本身的静态值来全局更改所有模型。否则,您可以通过覆盖所需的每个模型中的静态来基于每个模型进行此更改。要全局更改,您可以向AppServiceProvider
添加以下内容:
public function boot()
{
\Illuminate\Database\Eloquent\Model::$snakeAttributes = false;
}