如果列有 2 个连续的下划线,则使用访问器或修改器

Using an accessor or mutator if the column has 2 consecutive underscores

我的数据库中有一列 Started_Trading__c。我正在努力为这个领域使用访问器。到目前为止,我已经尝试了以下但没有成功。

public function getStartedTrading_cAttribute()

public function getStartedTrading__cAttribute()

public function getStarted_Trading__cAttribute()

public function getStarted_Trading_cAttribute()

什么是让访问器使用这种具有 2 个连续下划线的列名称的有效方法 __c

不幸的是,我无法控制数据库列名,所以理想情况下我想让它工作。

谢谢

Laravel 使用 Str::class 处理字符串,对于 mutator 的名称,它使用方法 camel.

以下字符串都将导致getStartedTradingCAttribute

Str::camel('get started trading c attribute')
Str::camel('get started_trading_c attribute')
Str::camel('           get started___trading__________c attribute')
Str::camel('get____started  __  trading   __c  ___attribute')

您需要声明的方法是getStartedTradingCAttribute()

更多详情(方法简单化)

public static function camel($value)
{
    return lcfirst(static::studly($value));
}

public static function studly($value)
{
    $key = $value;

    $value = ucwords(str_replace(['-', '_'], ' ', $value));

    return str_replace(' ', '', $value);
}

如您所见,所有 _(下划线)都替换为 (space),然后 studly()

中没有任何内容