laxity7 / yii2-json-field
Behavior that convert array to JSON before save data in model, and also convert JSON to an array after saving and retrieving data
Installs: 56 746
Dependents: 0
Suggesters: 0
Security: 0
Stars: 4
Watchers: 1
Forks: 0
Open Issues: 0
Requires
- php: ^7.4||^8.0
- ext-json: *
- yiisoft/yii2: 2.0.*
Requires (Dev)
- roave/security-advisories: dev-latest
This package is auto-updated.
Last update: 2024-10-30 01:37:16 UTC
README
This behavior adds advanced support for working with JSON data in Yii2 active record models. Behavior convert array to JSON before save data in model, and also convert JSON to an array after saving and retrieving data. Use JSON fields like normal fields with an array or object.
Install
Install via composer
composer require laxity7/yii2-json-field
How to use
To use JsonFieldBehavior, insert the following code to your ActiveRecord class:
/** @inheritdoc */ public function behaviors(): array { return [ [ 'class' => \laxity7\yii2\behaviors\JsonFieldBehavior::class, 'fields' => ['foo_data', 'bar_data'], ], ]; }
You can also pass the following parameters:
- jsonOptions
int
(by defaultJSON_UNESCAPED_UNICODE
) JSON constants can be combined to form options for json_encode(). - defaultValue
array|string
(by default'[]'
) The default value for attribute. This value by default will be stored in the database if the field value is empty. Ignored if [[skipEmpty]] is enabled. - skipEmpty
bool
(by defaulttrue
) Whether to skip a field if it's empty. When TRUE in the database, the field can be null, when FALSE will save an empty object ('[]' or see defaultValue) - asArray
bool
(by defaulttrue
) Decode JSON into an array or object.
So, the complete list of settings will look like this:
use laxity7\yii2\behaviors\JsonFieldBehavior; use yii\db\ActiveRecord; /** * @property int $id * @property array $foo_data * @property array $bar_data */ class Foo extends ActiveRecord { /** @inheritdoc */ public function behaviors(): array { return [ [ 'class' => JsonFieldBehavior::class, 'fields' => ['foo_data', 'bar_data'], 'jsonOptions' => JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE, 'skipEmpty' => false, 'defaultValue' => ['foo' => 'bar'], 'asArray' => true, ], ]; } // Based on these parameters may be approximately the code public function updateBar(int $id, array $barData): array { $model = self::findOne(['id' => $id]); $model->foo_data['foo'] = 'bar1'; $model->bar_data['bar'] = array_merge($model->bar_data['bar'], $barData); $model->save(); return $model->bar_data['bar']; } }