具有Symfony表单/实体字段名称'来自'

时间:2017-08-08 22:21:05

标签: php mysql forms symfony doctrine-orm

我有一个包含以下字段的实体:

/**
 * @ORM\Column(name="from", type="string", length=255, nullable=true)
 */
protected $from;

/**
 * @ORM\Column(name="to", type="string", length=255, nullable=true)
 */
protected $to;

我有一个包含以下字段的symfony表单:

->add(
        'from',
        'text',
        array(
            'label' => 'From',
            'attr' => array(
                'placeholder' => 'From whom',
            )
        )
    )->add(
        'to',
        'text',
        array(
            'label' => 'To',
            'attr' => array(
                'placeholder' => 'To whom',
            )
        )

当我在提交此表单后尝试持久化并刷新实体时,它会给出SQL查询语法错误:

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'from, to) VALUES ("from me", "to my wife"' at line 1

我知道这是因为我的表格字段|实体字段名称!,无论如何都要避免这个错误,而不用更改我的字段名称'来自'。如果我在任何地方都错了,请纠正我。

2 个答案:

答案 0 :(得分:3)

您肯定需要更改数据库中的两个列名。错误不是Doctrine,而是 FROM TO 都是MySQL保留字。必须引用保留字才能使用它们,但为什么不完全避免使用它们呢?如果您尝试对数据库运行本机查询,那么它很容易绊倒并具有类似的内容:

SELECT from FROM table;

Doctrine的美妙之处在于,您的实体名称不必与您的列名相匹配。所以你可以定义:

/**
 * @ORM\Column(name="from_whom", type="string", length=255, nullable=true)
 */
protected $from;

/**
 * @ORM\Column(name="to_whom", type="string", length=255, nullable=true)
 */
protected $to;

Doctrine抽象出MySQL层,所以即使你改变了列名,这个代码甚至不需要改变:

$entity->setFrom($from);
$entity->setTo($to);

尽管如此,这可能仍然会让您失望,因此我建议您更改实体成员变量。

答案 1 :(得分:2)

我不得不逃避实体列名称并且它完成了诀窍:

/**
 * @ORM\Column(name="`from`", type="string", length=255, nullable=true)
 */
protected $from;

/**
 * @ORM\Column(name="`to`", type="string", length=255, nullable=true)
 */
protected $to;
相关问题