在回答您的具体问题之前,让我们首先看看 Eloquent 变异器是如何工作的。
雄辩突变者如何工作
一切雄辩Model https://github.com/laravel/framework/blob/5.5/src/Illuminate/Database/Eloquent/Model.php#L1385-L1388-派生类有它们的__set() https://secure.php.net/manual/en/language.oop5.overloading.php#object.set and offsetSet() https://secure.php.net/manual/en/arrayaccess.offsetset.php方法来调用setAttribute https://github.com/laravel/framework/blob/5.5/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php#L517-L549方法负责设置属性值并在需要时改变它。
在设置值之前,它会检查:
- 自定义变异方法
- 日期字段
- JSONcastables 和字段
深入流程
通过理解这一点,我们可以简单地利用该流程并使用我们自己的自定义逻辑对其进行重载。这是一个实现:
<?php
namespace App\Models\Concerns;
use Illuminate\Database\Eloquent\Concerns\HasAttributes;
trait MutatesDatesOrWhatever
{
public function setAttribute($key, $value)
{
// Custom mutation logic goes here before falling back to framework's
// implementation.
//
// In your case, you need to check for date fields and mutate them
// as you wish. I assume you have put your date field names in the
// `$dates` model property and so we can utilize Laravel's own
// `isDateAttribute()` method here.
//
if ($value && $this->isDateAttribute($key)) {
$value = date('Y-m-d', strtotime($value));
}
// Handover the rest to Laravel's own setAttribute(), so that other
// mutators will remain intact...
return parent::setAttribute($key, $value);
}
}
不用说,您的模型需要使用此特征来启用该功能。
你不会需要它
If 变异日期 https://laravel.com/docs/5.5/eloquent-mutators#date-mutators是您需要拥有的唯一用例“动态命名的变体”,这根本不需要。正如您可能已经知道的那样noticed https://github.com/laravel/framework/blob/5.5/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php#L532,Eloquent 的日期字段可以由 Laravel 本身重新格式化:
class Whatever extends Model
{
protected $dates = [
'date_field_1',
'date_field_2',
// ...
];
protected $dateFormat = 'Y-m-d';
}
那里列出的所有字段都将按照以下格式进行格式化$dateFormat
。那么我们就不要重新发明轮子了。