eloquent 支持数组枚举转换吗?
Does eloquent support array enum casting?
Eloquent 允许 Enum Casting.
Eloquent also allows you to cast your attribute values to PHP enums.
To accomplish this, you may specify the attribute and enum you wish to
cast in your model's $casts property array:
use App\Enums\ServerStatus;
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'status' => ServerStatus::class,
];
Once you have defined the cast on your model, the specified attribute
will be automatically cast to and from an enum when you interact with
the attribute:
if ($server->status == ServerStatus::provisioned) {
$server->status = ServerStatus::ready;
$server->save();
}
是否可以在 eloquent 中对数组值使用枚举转换?
我有一个现有的 eloquent 模型,过去只有一种类型。现在需要支持多个。
Laravel 是否支持数组枚举转换或者这不可能?实现类似目标的替代方法是什么?
你可以使用spatie/laravel-enum
安装后:
composer require spatie/laravel-enum
您可以将它用于数组枚举转换,例如:
protected $casts = [
'status' => StatusEnum::class.':collection',
];
如果 status
可以为空,您可以:
protected $casts = [
'status' => StatusEnum::class.':collection,nullable',
];
这个包还有提供商验证规则和其他功能。
这里有一个有趣的pull request已经被合并了,但是我没有测试它。
Eloquent 允许 Enum Casting.
Eloquent also allows you to cast your attribute values to PHP enums. To accomplish this, you may specify the attribute and enum you wish to cast in your model's $casts property array:
use App\Enums\ServerStatus; /** * The attributes that should be cast. * * @var array */ protected $casts = [ 'status' => ServerStatus::class, ];
Once you have defined the cast on your model, the specified attribute will be automatically cast to and from an enum when you interact with the attribute:
if ($server->status == ServerStatus::provisioned) { $server->status = ServerStatus::ready; $server->save(); }
是否可以在 eloquent 中对数组值使用枚举转换?
我有一个现有的 eloquent 模型,过去只有一种类型。现在需要支持多个。
Laravel 是否支持数组枚举转换或者这不可能?实现类似目标的替代方法是什么?
你可以使用spatie/laravel-enum
安装后:
composer require spatie/laravel-enum
您可以将它用于数组枚举转换,例如:
protected $casts = [
'status' => StatusEnum::class.':collection',
];
如果 status
可以为空,您可以:
protected $casts = [
'status' => StatusEnum::class.':collection,nullable',
];
这个包还有提供商验证规则和其他功能。
这里有一个有趣的pull request已经被合并了,但是我没有测试它。