tigrov / yii2-pgsql
为 Yii2 优化的 PostgreSQL 架构
1.4.4
2021-10-10 09:29 UTC
Requires
- yiisoft/yii2: ^2.0.29
Requires (Dev)
- phpunit/phpunit: 4.8.34
README
为 Yii2 优化 PostgreSQL 架构。
Yii 2.0.14 及以上版本支持 array
和 json
数据库类型。
支持以下 ActiveRecord 模型类型
array
,Yii 2.0.14 及以上版本支持array
数据库类型json
,Yii 2.0.14 及以上版本支持json
数据库类型composite
,https://postgresql.ac.cn/docs/current/static/rowtypes.htmldomain
,https://postgresql.ac.cn/docs/current/static/sql-createdomain.html- 修复了类型
bit
,问题 #7682 - 将 Postgres 类型
timestamp
、date
和time
转换为 PHP 类型\DateTime
及反之。
限制
从版本 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