boldtrn / jsonb-bundle
一个为 Doctrine 添加对 PostgreSQL JSONB 列支持的库。
Requires
- php: >=5.3.3
- doctrine/dbal: ~2.4
Requires (Dev)
- doctrine/orm: >2.4,<2.6
- phpunit/phpunit: ~4.2
Suggests
- doctrine/orm: To use DQL functions
This package is auto-updated.
Last update: 2024-09-25 16:55:13 UTC
README
Doctrine 在 Doctrine DBAL 2.6 中实现了 jsonb 数据类型。我建议使用官方的 Doctrine 实现。如果您不能升级,请随意使用此包。它在我的当前生产环境中仍然有效。我将在某个时候升级到 doctrine 实现。 Doctrine 映射矩阵
此包扩展了 Doctrine 以使用 PostgreSQL 9.4 附加的 jsonb 数据类型。此包与 Symfony 完全兼容,但您不必使用 Symfony(请参阅 composer.json 以了解依赖项)。在使用此包之前,请确保您已安装至少为 9.4 版本的 PostgreSQL。此包允许创建 Jsonb 字段并在 Jsonb 字段上使用 @>、? 和 #>> 操作符。其他操作可以轻松添加。
我最近发现了 NativeQueries 的强大功能(http://doctrine-orm.readthedocs.org/en/latest/reference/native-sql.html)。目前我只在查询时使用 NativeQueries。以下是一个示例。
安装
步骤 1:下载包
打开命令行控制台,进入您的项目目录,然后执行以下命令以下载此包的最新稳定版本
$ composer require "boldtrn/jsonb-bundle:~1.1"
步骤 2:将新类型和函数添加到配置中
# config.yml doctrine: dbal: types: jsonb: Boldtrn\JsonbBundle\Types\JsonbArrayType mapping_types: jsonb: jsonb orm: dql: string_functions: JSONB_AG: Boldtrn\JsonbBundle\Query\JsonbAtGreater JSONB_HGG: Boldtrn\JsonbBundle\Query\JsonbHashGreaterGreater JSONB_EX: Boldtrn\JsonbBundle\Query\JsonbExistence
注意:有人遇到了上述配置的问题。他们遇到了以下异常
[Symfony\Component\Config\Definition\Exception\InvalidConfigurationException]
Unrecognized options "dql" under "doctrine.orm"
通过更改以下 dql 部分进行了修复(在 orm 和 dql 之间添加 entity_managers)
doctrine: orm: entity_managers: dql:
步骤 3:创建实体并使用 Jsonb 类型
/** * @Entity */ class Test { /** * @Id * @Column(type="string") * @GeneratedValue */ public $id; /** * @Column(type="jsonb") * * Usually attrs is an array, depends on you * */ public $attrs = array(); }
步骤 4.1:编写使用原生查询的存储库方法
$q = $this ->entityManager ->createNativeQuery( " SELECT t.id, t.attrs FROM Test t WHERE t.attrs @> 'value' " , $rsm);
您只需要根据 Doctrine 文档设置 $rsm ResultSetMapping。
步骤 4.2:编写查询 jsonb 的存储库方法,使用自定义 JSONB_FUNCTIONS
此示例展示了如何在 WHERE 子句中使用 contains 语句。= TRUE 是 Doctrine 需要的比较操作符的解决方案。
$q = $this ->entityManager ->createQuery( " SELECT t FROM E:Test t WHERE JSONB_AG(t.attrs, 'value') = TRUE " );
这将产生以下查询
SELECT t0_.id AS id0, t0_.attrs AS attrs1 FROM Test t0_ WHERE (t0_.attrs @> 'value') = true
此示例展示了如何查询值为 LIKE %d% 的值。结果可能是以下数据
id | attrs
----+--------------------------------------
4 | {"a": 1, "b": {"c": "abcdefg", "e": true}}
$q = $this ->entityManager ->createQuery( " SELECT t FROM E:Test t WHERE JSONB_HGG(t.attrs , '{\"b\",\"c\"}') LIKE '%d%' " );
这将产生以下查询
SELECT t0_.id AS id0, t0_.attrs AS attrs1 FROM Test t0_ WHERE (t0_.attrs #>> '{\"object1\",\"object2\"}') LIKE '%a%'
更多信息
由于 Doctrine 会将其视为参数占位符,所以 ? 操作符是通过调用其函数 jsonb_exists(column_name, value) 实现的。如果您想实现 ?| 和 ?& 操作符,必须分别使用 jsonb_exists_any(column_name, value) 和 jsonb_exists_all(column_name, value)。