yiisoft-custom/yii2-model-attribute-convert

Base on Yii2 BaseActiveRecord. Converts column from db format to model format while SELECT,oppositely way while INSERT or UPDATE

v1.2 2022-11-05 08:21 UTC

This package is auto-updated.

Last update: 2024-05-05 11:34:34 UTC


README

Attribute value converted between db format and Yii2 model format

Require yiisoft/yii2

Installation

composer require yiisoft-custom/yii2-model-attribute-convert

Notice & Important

Case the attribute set an converter in cast,it would be converted to model format while trigger EVENT_AFTER_FIND, and the model value strictly is already changed (e.g: db value format is json [1,2,3],with 'Array' converter , model format would bearray(1,2,3)). the result of these method calls would be effected :

isAttributeChanged(),
getOldAttribute(),
getOldAttributes(),
getDirtyAttributes()

But don't worry,we gotta the suitable calls instead while any attribute of model casted with a converter,list of mapper:

isAttributeChangedWithConverter()   -> isAttributeChanged()
getOldAttributeWithConverter()      -> getOldAttribute()
getOldAttributesWithConverter()     -> getOldAttributes()
getDirtyAttributesWithConverter()   -> getDirtyAttributes()

Usage

<?php
class Test extends ActiveRecord
{


    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['attribute_convert'] = [
            'class' => AttributeConverted::class,
            'cast' => [
                'order_no' => 'Array',
            ]
        ];

        return $behaviors;
    }
}

?>

Just used like other behavior class. Property $cast is key-value(eg: 'order_no' => 'Array'). Key is the attribute needs to be converted,and value is the converter,class name or string maps a class name would be fine