我正在使用带有Doctrine的Symfony 2,并且我有两个实体加入了多对多的关联.
假设我有两个实体:User和Group,db上的相关表是users,groups和users_groups.
假设我有两个实体:User和Group,db上的相关表是users,groups和users_groups.
我想在DQL中获得前十大人口最多的组,但我不知道在连接表(users_groups)上执行查询的语法.我已经查看了Doctrine手册,但我没有找到解决方案,我想我还有很多需要了解的DQL.
在普通的sql中,它将是:
select distinct group_id,count(*) as cnt from users_groups group by group_id order by cnt desc limit 10
能帮我把它翻译成DQL吗?
更新(课程):
/** * Entity\E_User * * @ORM\Table(name="users") * @ORM\Entity */ class E_User { /** * @ORM\ManyToMany(targetEntity="E_Group",cascade={"persist"}) * @ORM\JoinTable(name="users_groups",* joinColumns={@ORM\JoinColumn(name="user_id",referencedColumnName="id",onDelete="cascade")},* inverseJoinColumns={@ORM\JoinColumn(name="group_id",onDelete="cascade")} * ) */ protected $groups; /** * @var integer $id * * @ORM\Column(name="id",type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string $name * * @ORM\Column(name="name",type="string",length=255) */ private $name; /* ... other attributes & getters and setters ...*/ } /** * Entity\E_Group * * @ORM\Table(name="groups") * @ORM\Entity */ class E_Group { /** * @var integer $id * * @ORM\Column(name="id",type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string $name * * @ORM\Column(name="text",length=255) */ private $name; /* ... other attributes & getters and setters ...*/ }
如果没有看到实际的类,这并不容易,但通过猜测你有一个多对多的双向关系:
$dql = "SELECT g.id,count(u.id) as cnt FROM Entity\Group g " . "JOIN g.users u GROUP BY g.id ORDER BY cnt DESC LIMIT 10;"; $query = $em->createQuery($dql); $popularGroups = $query->getArrayResult();
更新:
您不必使用双向关系,您可以相反地查询:
$dql = "SELECT g.id,count(u.id) as cnt FROM Entity\User u " . "JOIN u.groups g GROUP BY g.id ORDER BY cnt DESC LIMIT 10;";