bluora / laravel-model-json-column
为 Laravel 的 Eloquent 模型提供 JSON 列支持。
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 列之前运行 inspectJson
方法,因为(我们重写的)newFromBuilder
方法不会在新的模型对象上调用。
$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)。有关更多信息,请参阅 许可证文件。