【问题标题】:Doctrine and quoting reserved word of MySqlMySql的教义和引用保留字
【发布时间】:2019-10-10 12:33:46
【问题描述】:

我的 Symfony 4.3 项目实体中有名为 Group 和 MySql 数据库中的表组。组是保留字。我有 3 个实体:用户、组、用户组。他们有关系: User -> OneToMany-> UserGroup and Group -> OneToMany -> UserGroup ( UserGroup 有附加属性,所以我不能使用 ManyToMany 关系)。当我尝试为 id=1 的用户获取组名时:

$entityManager = $this->getDoctrine()->getManager();
   $user = $entityManager->getRepository(User::class)
        ->find($id);
   $groups = $user->getUserGroups();

   foreach ($groups as $group) {
        $group_name = $group->getGroupId()->getName();
        echo $group_name, '<br>';
    }

我收到错误消息:

您有一个错误:执行“SELECT t0.id AS id_1, t0.name AS name_2 FROM group t0 WHERE t0.id = ?”时发生异常带参数 [1]:SQLSTATE[42000]:语法错误或访问冲突:1064 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 1 行的 'group t0 WHERE t0.id = 1' 附近使用正确的语法,代码:0

文档中有一个秘诀 (http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/basic-mapping.html#quoting-reserved-words) 如何启用对保留字的引用:

<?php
use Doctrine\ORM\Mapping\AnsiQuoteStrategy;

$configuration->setQuoteStrategy(new AnsiQuoteStrategy()); 

我不明白我必须在哪里使用此代码 - 在 EntityManager 中,在 Controller 中?以及如何获得 $configuration?

【问题讨论】:

  • 是什么让您认为您需要配置任何东西?当你跳过这部分时,有什么不工作吗?然后请分享有问题的代码(触发错误的代码)和一些版本信息
  • 我有 Symfony 4.3,你可以在我的问题正文中看到我的代码。
  • 您是否尝试在表格定义中使用反引号?
  • 是的,我试过了。无济于事。我已经根据stackoverflow.com/questions/10471234/… 实施我自己的 QuoteStrategy 解决了我的问题

标签: doctrine-orm doctrine symfony4


【解决方案1】:

我认为更好的解决方案是在Doctrine Documentation 中提到的实体定义中使用刻度。

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="App\Repository\GroupRepository")
 * @ORM\Table(name="`group`")
 */
class Group
{
    // ...
}

请注意,此方法仅在您使用默认报价策略时才有效。所以,删除quote_strategy参数或将其设置为doctrine.orm.quote_strategy.default

# config/packages/doctrine.yml

doctrine:
    # ...
    orm:
        quote_strategy: doctrine.orm.quote_strategy.default

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-30
    • 2021-05-24
    相关资源
    最近更新 更多