1

symfony2 でアプリケーションを作成しました。これまでのところ、ユーザーを認証するエンティティユーザー、エンティティゲスト、およびカテゴリ1 があります。

ユーザーは、(イベントのために)ゲストを保持するゲストとの OneToMany 関係を持ち、users.id を guest.user_id 変数にマッピングします。

同じ理由で、ユーザーもカテゴリとのOneToMany 関係を持っています。

多くのカテゴリに多くのゲストがいて、多くのゲストには多くのカテゴリがあるため、 GuestsはCategoriesと ManyToMany の関係にあります。

私はすべてを作成し、CRUD アクションは正常に機能し、ユーザーが追加したすべてのゲストを表示します。すべてのゲストが属するカテゴリを View アクションに追加したいと考えています。

私は混乱しています。ログインしたユーザーのすべてのゲストを取得するカスタム クエリを作成しました。

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
        ));
    }

カテゴリエンティティをクエリに追加しようとすると、例外が発生します。

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時間動作させようとしています(シリーズで:))。

4

1 に答える 1

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 %}
于 2012-08-14T08:55:35.003 に答える