双向关系出错

时间:2017-09-06 15:00:27

标签: php sql symfony doctrine-orm orm

我正在开发一个使用doctrine和Symfony的项目。 目前,当我尝试在具有双向关系的两个实体之间使用级联注释时,我遇到了一个问题。

我有两个实体。

MediaIndexer:

class MediaIndexer {
    /**
     * @var int
     * @ORM\Column(type="guid")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="UUID")
     */
    private $id;

    /**
     * @var ArrayCollection $identifiers
     * @ORM\OneToMany(targetEntity="CelebrityBundle\Entity\MediaIdentifier",
     *     mappedBy="indexer",
     *     cascade={"all"},
     *     orphanRemoval=true)
     */
    private $identifiers;

    // ...

    public function setValue($key, $value) {
        foreach ($this->getIdentifiers() as $identifier) {
            if ($identifier->getKey() == $key) {
                $identifier->setValue($value);

                return $this;
            }
        }

        $identifier = new MediaIdentifier();
        $identifier->setKey($key)
                   ->setValue($value)
                   ->setIndexer($this);

        $this->addIdentifier($identifier);

        return $this;
    }
}

MediaIdentifier:

class MediaIdentifier {
    /**
     * @var int
     * @ORM\Column(type="guid")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="UUID")
     */
    private $id;

    /**
     * @var MediaIndexer $indexer
     * @ORM\ManyToOne(targetEntity="CelebrityBundle\Entity\MediaIndexer", inversedBy="identifiers")
     * @ORM\JoinColumn(onDelete="CASCADE", referencedColumnName="id")
     */
    private $indexer;

    /**
     * @var string $content
     * @ORM\Column(name="key", type="string", length=255, nullable=false)
     */
    private $key;

    /**
     * @var int $type
     * @ORM\Column(name="value", type="text", nullable=false)
     */
    private $value;
    // ...
}

(实际上,这些类用于在DB中构造“关联数组”。

我用一些小代码尝试了这种关系:

public function testAction()
{
    $indexer = new MediaIndexer();

    $indexer->setValue("screenName", "katyperry");
    $indexer->setValue("pageId", "00000");

    $this->getDoctrine()->getManager()->persist($indexer);
    $this->getDoctrine()->getManager()->flush();
}

而且,当我运行此代码时,我遇到了错误:

An exception occurred while executing 'INSERT INTO medias_identifiers (id, key, value, indexer_id) VALUES (?, ?, ?, ?)' with params ["b8a4c4e3-9312-11e7-93c0-e55e28abe26b", "screenName", "katyperry", "b8a47f19-9312-11e7-93c0-e55e28abe26b"]:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'key, value, indexer_id) VALUES ('b8a4c4e3-9312-11e7-93c0-e55e28abe26b', 'screenN' at line 1

你对这个问题有任何想法吗?

由于

1 个答案:

答案 0 :(得分:3)

KEYreserved word in MariaDB。尝试使用backticks围绕密钥的定义:

/**
 * @var string $content
 * @ORM\Column(name="`key`", type="string", length=255, nullable=false)
 */
private $key;