yiisoft-custom / yii2-model-attribute-convert
基于 Yii2 BaseActiveRecord。在 SELECT 时将列从数据库格式转换为模型格式,在 INSERT 或 UPDATE 时反向转换
v1.2
2022-11-05 08:21 UTC
Requires
- php: >=7.0
- yiisoft/yii2: 2.0.*
This package is auto-updated.
Last update: 2024-09-05 12:11:55 UTC
README
在数据库格式和 Yii2 模型格式之间转换属性值
需要 yiisoft/yii2
安装
composer require yiisoft-custom/yii2-model-attribute-convert
注意 & 重要
如果属性设置了转换器,则在触发 EVENT_AFTER_FIND
时会转换为模型格式,并且模型值已严格更改(例如:数据库值格式为 json [1,2,3]
,使用 'Array' 转换器,模型格式将是 array(1,2,3)
)。这些方法调用的结果将受到影响
isAttributeChanged(),
getOldAttribute(),
getOldAttributes(),
getDirtyAttributes()
但是不必担心,我们提供适合任何带有转换器的模型属性的调用,映射列表
isAttributeChangedWithConverter() -> isAttributeChanged()
getOldAttributeWithConverter() -> getOldAttribute()
getOldAttributesWithConverter() -> getOldAttributes()
getDirtyAttributesWithConverter() -> getDirtyAttributes()
用法
<?php class Test extends ActiveRecord { public function behaviors() { $behaviors = parent::behaviors(); $behaviors['attribute_convert'] = [ 'class' => AttributeConverted::class, 'cast' => [ 'order_no' => 'Array', ] ]; return $behaviors; } } ?>
就像使用其他行为类一样使用。属性 $cast
是键值(例如:'order_no' => 'Array'
)。键
是需要转换的属性,值
是转换器,可以是类名或指向类名的字符串