【问题标题】:How to retrieve categories using a DQL query from a symfony2 blog?如何使用 symfony2 博客中的 DQL 查询检索类别?
【发布时间】:2012-08-10 04:14:05
【问题描述】:

我在 symfony2 中创建了一个应用程序。到目前为止,我有一个实体 Users 对用户进行身份验证,一个实体 Guests 和一个 Category 实体。

UsersGuests 具有 OneToMany 关系,该关系保留来宾(针对事件),将 users.id 映射到 guest.user_id 变量。

出于同样的原因,

用户也与类别存在 OneToMany 关系。

GuestsCategories 具有多对多关系,因为许多类别中有许多客人,而且许多客人有许多类别。

我已经创建了所有内容,并且 CRUD 操作成功地向我显示了用户添加的所有客人。我想添加每个客人属于查看操作的类别。

我很困惑。我做了一个自定义查询来检索登录用户的所有客人:

public function indexAction()
    {
       $user = $this->get('security.context')->getToken()->getUser();
       $userId = $user->getId();

       $em = $this->getDoctrine()->getEntityManager();
       $query = $em->createQuery("SELECT g
                                  FROM Acme\SomethingBundle\Entity\Guest g
                                  INNER JOIN g.user u
                                  WHERE u.id = :userId
                                  ORDER BY g.surname ASC");
        $query->setParameter('userId', $userId); 
        $entities = $query->getResult();

        return $this->render('AcmeSomethingBundle:Guest:index.html.twig', array(
            'entities' => $entities
        ));
    }

如果我尝试将 Category 实体添加到查询中,我会遇到异常:

public function indexAction()
        {
           $user = $this->get('security.context')->getToken()->getUser();
           $userId = $user->getId();

           $em = $this->getDoctrine()->getEntityManager();
           $query = $em->createQuery("SELECT g , c
                                      FROM Acme\SomethingBundle\Entity\Guest g,
                                           Acme\SomethingBundle\Entity\Category c
                                      INNER JOIN g.user u
                                      WHERE u.id = :userId
                                      ORDER BY g.surname ASC");
            $query->setParameter('userId', $userId); 
            $entities = $query->getResult();

            return $this->render('AcmeSomethingBundle:Guest:index.html.twig', array(
                'entities' => $entities
            ));
        }

请帮忙。我一直在努力让它工作 6 个小时(在一个系列中:))。

【问题讨论】:

  • SQLSTATE[42S22]:找不到列:1054 'on 子句'中的未知列 'g0_.user_id' 500 内部服务器错误 - PDOException
  • 尝试运行“php app/console dictionary:schema:update --force”
  • 无需更新 - 您的数据库已与当前实体元数据同步。
  • 我相信我的查询实际上是错误的。我需要额外的左连接吗?

标签: symfony doctrine-orm dql


【解决方案1】:
SELECT g
FROM Acme\MarriBundle\Entity\Guest g
LEFT JOIN g.user u
WHERE u.id = :userId
ORDER BY g.surname ASC

查询是对的,错误的是树枝编码。我必须创建一个循环,因为类别是一个数组

{% for category in entity.categories %}
{{ category.name }}
{% endfor %}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-16
    相关资源
    最近更新 更多