hnhdigital-os/laravel-model-json

为Laravel的Eloquent模型提供JSON列支持。

v1.5.0 2018-12-20 23:38 UTC

This package is auto-updated.

Last update: 2024-09-21 20:56:35 UTC


README

    __                                __    _______ ____  _   __
   / /   ____ __________ __   _____  / /   / / ___// __ \/ | / /
  / /   / __ `/ ___/ __ `/ | / / _ \/ /_  / /\__ \/ / / /  |/ / 
 / /___/ /_/ / /  / /_/ /| |/ /  __/ / /_/ /___/ / /_/ / /|  /  
/_____/\__,_/_/   \__,_/ |___/\___/_/\____//____/\____/_/ |_/   
                                                                

通过基于对象的接口为模型添加对JSON数据类型列的支持。

Latest Stable Version Total Downloads Latest Unstable Version Built for Laravel License

Build Status StyleCI Test Coverage Issue Count Code Climate

此包由澳大利亚精品开发商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]];

使用true调用getDirty将使用点符号提供更改。

print_r($user->getDirty(true));

将输出

array(
    'settings' => "{"showProfilePicture":true,"options":{"option1":"red","option2":1}}",
    'settings.options' => array('option2' => 1)
)

注意

如果您使用findOrNewfirstOrNewfirstOrCreateupdateOrCreate方法,在使用任何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)。有关更多信息,请参阅许可文件