繁体   English   中英

API 平台:无法在 MySQL 中使用 json 数据类型

[英]API Platform: Can't get using a json data type with MySQL to work

我是 API 平台的新手,并试图获取一个 json 数据属性以作为 json 对象持久保存到 MySQL。 我查看了 API 平台文档并用谷歌搜索了答案,但没有找到任何答案。

我的设置:

MySQL 列定义为:

`document` json DEFAULT NULL 

我定义了一个“MyEntity”PHP 对象,json 属性描述如下:

/**
 * @var json 
 *
 * @ORM\Column(type="json")
 */
private $document;

/**
 * Get document.
 *
 * @return json
 */
public function getDocument()
{
    return $this->document;
}

/**
 * Set document.
 *
 * @param json $document
 *
 * @return MyEntity
 */
public function setDocument($document)
{
    $this->document = $document;

    return $this;
}

现在,当该 URL 显示 MyEntity 的默认界面并执行 POST 以使用此 json-ld 创建它时(简化为省略其他列):

{
    "document": "{"test": "value"}"
}

我收到 400 Bad Request 错误

{
    "@context": "/contexts/Error",
    "@type": "hydra:Error",
    "hydra:title": "An error occurred",
    "hydra:description": "Syntax error",
    "trace": [
    {
        "namespace": "",
        "short_class": "",
        "class": "",
        "type": "",
        "function": "",
        "file": "/Library/WebServer/Documents/test/vendor/symfony/symfony/src/Symfony/Component/Serializer/Encoder/JsonDecode.php",
        "line": 78,
        "args": []
    },
...

我转义了双引号(这对我来说似乎很奇怪,你需要这样做,因为它本身是一个描述另一个 json 对象的 json),如下所示:

{
    "document": "{\"test\": \"value\"}"
}

并再次执行 POST:

我收到一个带有不同内部错误的 400 Bad Request Error:

{
    "@context": "/contexts/Error",
    "@type": "hydra:Error",
    "hydra:title": "An error occurred",
    "hydra:description": "Could not denormalize object of type AppBundle\\Entity\\json, no supporting normalizer found.",
    "trace": [
    {
        "namespace": "",
        "short_class": "",
        "class": "",
        "type": "",
        "function": "",
        "file": "/Library/WebServer/Documents/test/vendor/symfony/symfony/src/Symfony/Component/Serializer/Serializer.php",
       "line": 295,
       "args": []
    },  
...

因此,看起来 API 平台无法识别 JSON 数据类型,并期望为其提供自定义实体......对我来说似乎不合适。

我还查看了学说的类型,据我所知,API 平台使用并找到了以下信息:

一些供应商具有原生 JSON 类型,Doctrine 会尽可能使用它,否则会默默地回退到供应商的文本类型,以确保最有效的存储要求。 如果供应商没有本机 JSON 类型,则此类型需要 SQL 列注释提示,以便可以从数据库对其进行逆向工程。 Doctrine 无法在不支持列注释的供应商上正确映射回这种类型,而是会回退到文本类型。

但由于 MySQL 确实支持 JSON 数据类型,我认为这会奏效,但显然不行。 任何关于 API 平台如何使用 MYSQL 处理 JSON 数据类型的帮助将不胜感激。

由于您的 PHPdoc 类型提示,您收到此错误。 Api-platform 在规范化期间使用 PHPdoc 元数据。

PHP 中没有“json”数据类型这样的东西,所以它会在同一个命名空间中寻找一个类。

来自 Doctrine 文档:

从数据库中检索到的值总是使用 PHP 的 json_decode() 函数转换为 PHP 的数组或空类型。

所以你应该改变你的 PHPDoc typehint 到array

/**
 * @var array
 *
 * @ORM\Column(type="json")
 */
private $document;

/**
 * Get document.
 *
 * @return array
 */
public function getDocument()
{
    return $this->document;
}

/**
 * Set document.
 *
 * @param array $document
 *
 * @return MyEntity
 */
public function setDocument($document)
{
    $this->document = $document;

    return $this;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM