bluora / laravel-model-json
v1.5.0
2018-12-20 23:38 UTC
Requires
- php: >=5.6.0
- illuminate/support: 4.*|5.*
Requires (Dev)
- codeclimate/php-test-reporter: dev-master
- illuminate/database: 4.*|5.*
- phpmd/phpmd: @stable
- phpunit/phpunit: 5.*
- symfony/process: ~2.3
README
__ __ _______ ____ _ __
/ / ____ __________ __ _____ / / / / ___// __ \/ | / /
/ / / __ `/ ___/ __ `/ | / / _ \/ /_ / /\__ \/ / / / |/ /
/ /___/ /_/ / / / /_/ /| |/ / __/ / /_/ /___/ / /_/ / /| /
/_____/\__,_/_/ \__,_/ |___/\___/_/\____//____/\____/_/ |_/
通过基于对象的接口为模型添加JSON数据类型列的支持。
此包由澳大利亚精品开发商H&H|Digital开发。访问我们 hnh.digital。
安装
$ composer require hnhdigital-os/laravel-model-json ~1.0
使用方法
基本
通过一个特性公开了这个功能,允许你定义包含JSON数据的列。当模型创建时,它会使用指定的列名生成方法。然后你可以直接获取和设置属性。
use Bluora\LaravelModelJson\JsonColumnTrait; class User extends Model { use JsonColumnTrait; protected $json_columns = [ 'settings' ]; }
然后可以通过对象属性来检索或设置JSON列的值。
假设我们在settings
JSON列中存储了一个数据数组
['showProfilePicture' => true, 'options' => ['option1' => 'red']];
获取这些值就像这样简单
echo $user->settings()->showProfilePicture."\n"; echo $user->settings()->options['option1'];
将输出
1
red
你可以更新任何变量或添加一个新变量
$user->settings()->options['option2'] = 1; $user->save();
并将更新JSON对象为以下数组
['showProfilePicture' => true, 'options' => ['option1' => 'red', 'option2' => 1]];
调用getDirty
并传入true
将使用点表示法提供更改。
print_r($user->getDirty(true));
将输出
array(
'settings' => "{"showProfilePicture":true,"options":{"option1":"red","option2":1}}",
'settings.options' => array('option2' => 1)
)
注意
如果你使用了findOrNew
、firstOrNew
、firstOrCreate
或updateOrCreate
方法,你应该在使用任何JSON列作为newFromBuilder
方法(我们重写了该方法)的参数之前运行inspectJson
方法。
$model = Model::firstOrNew(['name' => 'example']); $model->inspectJson();
默认值
你可以在模型上使用$json_defaults
属性为json属性定义默认值。
你指定属性名和默认值,如果名称不存在,它将在创建对象时被添加。
protected $json_defaults = [
'settings' => ['showProfilePicture' => 0]
];
保存更改
当调用保存事件时,特性将原始属性值设置为最新的JSON编码值。
如果你已经使用了默认值,你可以通过将特定json列的选项no_saving_default_values
设置为true来阻止这些值被保存到数据库中
protected $json_options = [
'settings' => ['no_saving_default_values' => true]
];
贡献
请参阅 CONTRIBUTING 了解详情。
致谢
许可
MIT许可(MIT)。请参阅 许可文件 了解更多信息。