2013-10-26 256 views
0

我编辑线程放置更多信息。学说多对多关系

我有“用户”实体和“Rol”实体,我正在努力工作收集用户的角色。

在我定义的用户实体:

/** 
* @ManyToMany(targetEntity="AppsManantiales\CommonBundle\Entity\Perfil") 
* @JoinTable(name="usuarios_perfiles", 
*  joinColumns={@JoinColumn(name="idUsuario", referencedColumnName="idusuario")}, 
*  inverseJoinColumns={@JoinColumn(name="idPerfil", referencedColumnName="idperfil")} 
*) 
*/ 
protected $perfiles; 

并在构造函数:

public function __construct(){ 
     $this->perfiles = new \Doctrine\Common\Collections\ArrayCollection(); 
     $this->contacto = new \Doctrine\Common\Collections\ArrayCollection(); 
    } 

类的命名空间放前:

use AppsManantiales\CommonBundle\Entity\Perfil; 

当执行:

php app/console generate:doctrine:entities CommonBundle 

一个错误出现:

[Doctrine\Common\Annotations\AnnotationException]                     
    [Semantical Error] The annotation "@ManyToMany" in property AppsManantiales\CommonBundle\Entity\Usuario::$perfiles was never impo 
    rted. Did you maybe forget to add a "use" statement for this annotation? 

任何想法?

+0

ü可以显示完整的实体代码?你如何使用mapper? – DaunnC

+0

哦,我已经更新了我的答案。所以它是'Symfony2' :) – DaunnC

+0

检查@ManyToMany或@ORM \ ManyToMany。这个错误似乎是该教义无法找到这个特定的注释。 – busypeoples

回答

0

第一部分:所以在这种情况下,您在Role实体和User实体之间得到了多对多的关系。首先,在生成后检查r个实体是否正确。这里u能找到建立不同的关系基本概念的例子:http://docs.doctrine-project.org/en/latest/reference/association-mapping.html & & http://docs.doctrine-project.org/en/2.0.x/reference/association-mapping.html(第二个有原则的查询示例的详细信息)

你问题的第二部分:建立正确的关系,你的User要去的选择查询后水木清华像:

$user = $em->createQueryBuilder() 
    ->select('u, r') 
    ->from('YourBundle:User', 'u') 
    ->innerJoin('u.roles', 'r') 
    ->where('u.id IN (:ids)') 
    ->setParameter('ids', $ids) 
    ->getQuery() 
    ->getResult(); 

而且为u猜测,U可以与您的访问者的帮助下得到的角色:$user->getRoles()

PS是的,如果所有的实体都是正确的,你可以手动添加方法。

EDITED

哦SRY,我忘了,u使用Symfony2。因此,在默认情况下在你的实体,你长了这样一行:

use Doctrine\ORM\Mapping as ORM; 

如u可以看到,U使用的所有注释是前缀@ORM\。 exmpls:

/** 
* @ORM\Id 
* @ORM\Column(type="integer") 
* @ORM\GeneratedValue(strategy="AUTO") 
*/ 

所以只需添加前缀@ORM和结果:

/** 
* @ORM\ManyToMany(targetEntity="AppsManantiales\CommonBundle\Entity\Perfil") 
* @ORM\JoinTable(name="usuarios_perfiles", 
*  joinColumns={@ORM\JoinColumn(name="idUsuario", referencedColumnName="idusuario")}, 
*  inverseJoinColumns={@ORM\JoinColumn(name="idPerfil", referencedColumnName="idperfil")} 
*) 
*/ 
+0

感谢您的回复。我改变线程的主体。带着一个新问题。 – ramiromd