在学说中插入 json 不起作用

ElG*_*_76 3 php json doctrine symfony doctrine-orm

我调用了一个 JSON API,它将数据发回给我,我想使用 Symfony 中的 Doctrine 将此 JSON 插入到我的 MariaDB 数据库中。

我检索的 JSON 是一个对象数组,我在互联网上遵循了几个示例(例如:Doctrine array vs simple_array vs json_array)但没有一个有效,我不知道我的问题是什么。

这是我的代码:

    $client = new Client();
    $request = $client->request('GET', 'mylink.com');
    $response = $request->getBody();
    $livescore = json_decode($response, true);

    $array = [];
    foreach($livescore as $value) {
        if($value['match_hometeam_name'] === 'Lyon' || $value['match_awayteam_name'] === 'Lyon') {
            $array = $value;
            break;
        }
    }

    $livescoreObj = new Livescore();
    $livescoreObj->setDateRafraichissement(new \DateTime());
    $livescoreObj->setMatch($array);

    $this->entityManager->persist($livescoreObj);
    $this->entityManager->flush($livescoreObj);

    return new JsonResponse($array);
Run Code Online (Sandbox Code Playgroud)

我的实体:

    <?php

namespace SGBundle\Entity;
use Doctrine\ORM\Mapping as ORM;

/**
 * Livescore
 *
 * @ORM\Entity()
 */
class Livescore
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     * @ORM\Column(type="integer", options={"unsigned":true}, nullable=false)
     *
     * @var int
     */
    private $id;

    /**
     * @ORM\Column(type="json_array", nullable=true)
     *
     * @var string
     */
    private $match;

    /**
     * @var \DateTime
     *
     * @ORM\Column(type="datetime")
     */
    private $dateRafraichissement;

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

    /**
     * @param mixed $id
     */
    public function setId($id)
    {
        $this->id = $id;
    }

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

    /**
     * @param mixed $match
     */
    public function setMatch($match)
    {
        $this->match = $match;
    }

    /**
     * @return \DateTime
     */
    public function getDateRafraichissement()
    {
        return $this->dateRafraichissement;
    }

    /**
     * @param \DateTime $dateRafraichissement
     */
    public function setDateRafraichissement($dateRafraichissement)
    {
        $this->dateRafraichissement = $dateRafraichissement;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的错误:

SQLSTATE[42000]: 语法错误或访问冲突:1064 Error syntax near 'match, date_rafraichissement) VALUES ('{\"match_id\":\"257194\",\"country_id\":\' at line 1

预先感谢您的帮助

lxg*_*lxg 6

您的问题是$match属性:MATCH是MySQL 中的保留字,在查询中使用时需要引用。

由于某些原因,Doctrine 不会自动引用字段。但是您可以告诉它在构建查询时引用字段名称。请尝试以下操作:

/**
 * @ORM\Column(name="`match`", type="json_array", nullable=true)
 *
 * @var string
 */
private $match;
Run Code Online (Sandbox Code Playgroud)