我在symfony2中创建了一个应用程序。到目前为止,我有一个实体用户来验证用户,实体来宾和类别。
用户与来宾具有OneToMany关系,用于保留来宾(针对某个事件),将users.id映射到guests.user_id变量。
由于同样的原因,用户与类别也有OneToMany关系。
来宾与类别具有ManyToMany关系,因为许多类别中有许多来宾,许多来宾有许多类别。
我创建了所有内容,CRUD操作成功地向我显示了用户添加的所有访客。我想添加每个guest虚拟机属于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小时(在一系列:))。
答案 0 :(得分:1)
SELECT g
FROM Acme\MarriBundle\Entity\Guest g
LEFT JOIN g.user u
WHERE u.id = :userId
ORDER BY g.surname ASC
查询是对的,错误的是twig编码。我必须创建一个循环,因为类别是一个数组
{% for category in entity.categories %}
{{ category.name }}
{% endfor %}