首页 > 解决方案 > 使用学说将 JSON 数据存储到 TEXT mysql 列中

问题描述

我有一个具有 TEXT (MySQL) 属性的实体

<?php

namespace App\Entity;

use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Mapping\Table;
use Doctrine\ORM\Mapping\Index;
use ApiPlatform\Core\Annotation\ApiProperty;


/**
 * @ApiResource(
 *     attributes={},
 *     collectionOperations={
 *         "get"={},
 *         "post"={
 *              "access_control"="is_granted('ROLE_COMPANY')"
 *           },
 *     },
 *     itemOperations={
 *         "get"={},
 *         "put"={"access_control"="is_granted('ROLE_COMPANY')"},
 *      }
 * )
 * @ORM\Entity(
 *     repositoryClass="App\Repository\SettingRepository",
 *     )
 * @ORM\Table(
 *     indexes={@Index(name="domain_idx", columns={"domain"})}
 * )
 */
class Setting
{
    /**
     * @var Uuid
     * @ApiProperty(identifier=true)
     * @ORM\Id
     * @ORM\Column(type="string")
     * @ORM\GeneratedValue(strategy="NONE")
     */
    private $identifier;

    /**
     * @ORM\Column(type="text", nullable=true)
     */
    private $data = array();


    /**
     * @ORM\Column(type="string", nullable=true)
     */
    private $domain = array();



    public function getData()
    {
        if($this->data == null) return array();
        $data = unserialize($this->data);

        return $data;
    }

    public function setData($data): self
    {
        $this->data = serialize($data);
        return $this;
    }

    /**
     * @return mixed
     */
    public function getIdentifier()
    {
        return $this->identifier;
    }

    /**
     * @param mixed $key
     */
    public function setIdentifier($identifier): self
    {
        $this->identifier = $identifier;
        return $this;
    }

    /**
     * @return mixed
     */
    public function getDomain()
    {
        return $this->domain;
    }

    /**
     * @param mixed $domain
     */
    public function setDomain($domain): self
    {
        $this->domain = $domain;
        return $this;
    }



}

如果我尝试使用以下参数结构调用服务,它可以正常工作:

{
  "data": "testData",
  "identifier": "testIdentifier",
  "domain": "domain1"
}

但是如果我想存储一个嵌入的 JSON 字符串,例如:"data": {"temp": 123}

我收到以下错误: hydra:description": "\"data\" 属性的类型必须是 \"string\", \"array\" given.",

我试图在 setData 方法中将对象转换为字符串。但是这个方法不会被调用。它接缝,API 平台检测到错误的类型并引发异常。

我发现了一些评论,有必要装饰属性: https ://api-platform.com/docs/core/serialization/#decorating-a-serializer-and-adding-extra-data

谁能给我一个例子?这没用!序列化和反序列化属性数据的正确位置在哪里?

有人有想法吗?亲切的问候

标签: api-platform.com

解决方案


您需要json在 MySQL 中将列类型设置为。它应该按预期运行。

/**
 * @var array Additional data describing the setting. 
 * @ORM\Column(type="json", nullable=true)
 */
    private $data = null;

我认为null比空数组更一致,但这是您的选择。


推荐阅读