tigrov/yii2-pgsql

为 Yii2 优化的 PostgreSQL 架构

安装次数: 50,387

依赖者: 0

建议者: 0

安全性: 0

星标: 34

关注者: 7

分支: 6

开放问题: 2

类型:yii2-extension

1.4.4 2021-10-10 09:29 UTC

This package is auto-updated.

Last update: 2024-09-10 15:48:26 UTC


README

为 Yii2 优化 PostgreSQL 架构。

Yii 2.0.14 及以上版本支持 arrayjson 数据库类型。

支持以下 ActiveRecord 模型类型

Latest Stable Version Build Status

限制

从版本 1.2.0 开始,需要 Yii 2.0.14 及以上。
如果使用 Yii 2.0.13 及以下版本,可以使用版本 1.1.11。

安装

通过 composer 安装此扩展是首选方式。

运行以下命令

php composer.phar require --prefer-dist tigrov/yii2-pgsql

或添加

"tigrov/yii2-pgsql": "~1.0"

到您的 composer.json 文件的 require 部分。

配置

扩展安装后,将以下代码添加到您的应用程序配置中

return [
    //...
    'components' => [
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'pgsql:host=localhost;dbname=<database>',
            'username' => 'postgres',
            'password' => '<password>',
            'schemaMap' => [
                'pgsql'=> 'tigrov\pgsql\Schema',
            ],
        ],
    ],
];

指定表的所需类型

CREATE TABLE public.model (
    id serial NOT NULL,
    attribute1 text[],
    attribute2 jsonb,
    attribute3 timestamp DEFAULT now(),
    CONSTRAINT model_pkey PRIMARY KEY (id)
);

配置模型的规则

/**
 * @property string[] $attribute1 array of string
 * @property array $attribute2 associative array or just array
 * @property integer|string|\DateTime $attribute3 for more information about the type see \Yii::$app->formatter->asDatetime()
 */
class Model extends ActiveRecord
{
    //...
    public function rules()
    {
        return [
            [['attribute1'], 'each', 'rule' => ['string']],
            [['attribute2', 'attribute3'], 'safe'],
        ];
    }
}

用法

然后可以按以下方式将数组、JSON 和时间戳类型保存到数据库

/**
 * @var ActiveRecord $model
 */
$model->attribute1 = ['some', 'values', 'of', 'array'];
$model->attribute2 = ['some' => 'values', 'of' => 'array'];
$model->attribute3 = new \DateTime('now');
$model->save();

并在您的代码中使用它们

/**
 * @var ActiveRecord $model
 */
$model = Model::findOne($pk);
$model->attribute1; // is array
$model->attribute2; // is associative array (decoded json)
$model->attribute3; // is \DateTime

组合类型

许可证

MIT