【发布时间】:2018-07-16 08:40:58
【问题描述】:
我正在使用最新的 CakePHP 版本,并且想用夹具做一些 PHPunit 测试。我的 MariaDB 版本不支持 JSON 数据类型,因此我将 TEXT 数据类型用于应该存储 json 数据的表列。例如,我有一个名为 Items 的表,其中有一列 json_options。我已将 CakePHP 的预定义自定义 JSON 数据类型包含到我的表模型中:
// in src/Model/Table/ItemsTable.php
protected function _initializeSchema(TableSchema $schema)
{
$schema->columnType('json_column', 'json');
return $schema;
}
现在我正在使用 Bake 控制台生成 Fixtures 并从表中导入一些记录:
bake fixture items -c fixture -r
(简化的)结果是这样的:
// in /tests/Fixture/ItemsFixture.php
public $fields = [
'id' => ['type' => 'integer', 'length' => 10, 'unsigned' => true, 'null' => false, 'default' => null, 'comment' => '', 'autoIncrement' => true, 'precision' => null],
'json_options' => ['type' => 'text', 'length' => null, 'null' => true, 'default' => null, 'collate' => 'utf8_general_ci', 'comment' => '', 'precision' => null],
public $records = [
'id' => 1
'options' => array(
'someKey' => 'someValue'
)
]
现在的问题是:json_options 列在 $fields-definition 中具有 text 类型,但记录包含一个数组而不是字符串。这会导致运行测试时出现异常:
Exception: Cannot convert value to string in src\Database\Type\StringType.php
如果我将类型从 text 更改为 json,则测试正常。但是每次导入记录后,手动更改所有表夹具中的类型是很多工作。
那么 Bake shell 是否有可能在 Fixture 生成期间检测到 json 列并使用正确的类型?或者有没有办法即时更改 Fixture 中的模式定义,例如在 ItemsControllerTest.php 的 setUp() 方法中?或者任何其他提示如何处理 Fixtures 中的 json 数据?
【问题讨论】:
标签: json cakephp cakephp-3.0 fixtures