Php 使用Symfony表单/实体字段名时出现问题';从';

Php 使用Symfony表单/实体字段名时出现问题';从';,php,mysql,forms,symfony,doctrine-orm,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; ->add( 'from', 'text',

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

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

/**
 * @ORM\Column(name="to", type="string", length=255, nullable=true)
 */
protected $to;
->add(
        'from',
        'text',
        array(
            'label' => 'From',
            'attr' => array(
                'placeholder' => 'From whom',
            )
        )
    )->add(
        'to',
        'text',
        array(
            'label' => 'To',
            'attr' => array(
                'placeholder' => 'To whom',
            )
        )
我有一个symfony表单,其中包含以下字段:

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

/**
 * @ORM\Column(name="to", type="string", length=255, nullable=true)
 */
protected $to;
->add(
        'from',
        'text',
        array(
            'label' => 'From',
            'attr' => array(
                'placeholder' => 'From whom',
            )
        )
    )->add(
        'to',
        'text',
        array(
            'label' => 'To',
            'attr' => array(
                'placeholder' => 'To whom',
            )
        )
在提交此表单后尝试持久化和刷新实体时,会出现SQL查询SYNTAX错误:

SQLSTATE[42000]:语法错误或访问冲突:1064您的SQL语法有错误;查看与您的MySQL服务器版本对应的手册,了解使用第1行“from,to”值(“from”,“to my layer”)的正确语法


我知道这是因为我的表单字段|实体字段名!在不更改我的字段名“from”的情况下,是否有任何方法可以避免此错误。如果我在任何地方出错,请更正我。

您肯定需要更改数据库中的两个列名。此错误与条令无关,但与from这两个事实有关>TO是MySQL保留字。使用保留字时必须引用它们,但为什么不完全避免它们呢?如果您尝试对数据库运行本机查询,很容易出错,出现如下情况:

SELECT from FROM table;
原则的美妙之处在于,实体名称不必与列名称匹配。因此,您可以定义:

/**
 * @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);

不过,这可能仍然会使您在DQL查询中出错,因此我建议您也更改实体成员变量。

我必须转义实体列名,它做到了:

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

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

如何管理CRUD操作中的create函数我做了一些类似的事情,把名字从源代码和源代码和目的地都改了。记住,如果你使用QueBueBu建器,这仍然会给你DQL问题。你不想改变列名吗?这看起来是一个更大的头痛。如你所说,我将来会遇到很多问题。谢谢@JasonRoman!请查看我的答案,现在ti不会抛出错误。如果我的方法有任何问题,请告诉我。