如何使用Symfony2从数据库中检索子记录?

时间:2015-05-28 14:58:04

标签: symfony doctrine

我有两个表,一个map_families表和一个map_contacts表。这两个表之间存在一对多的关系,当显示Family记录时,我想显示它来自map_contacts表的任何子记录。

目前,我有这段代码:

        $familylist = $dm->createQuery('
        SELECT mf.id, mf.surname, mf.firstName, mf.email, mf.phone, mc.id AS memID, mc.firstName AS memFirstName, mc.surname AS memSurname
        FROM MyBundle:MapFamilies mf
        LEFT JOIN MyBundle:MapContacts mc WHERE mf.id = mc.family
        WHERE mf.centre = :centre
        ORDER BY mf.surname ASC, mf.firstName ASC'
        )->setParameter('centre', $centre);

        $famlist = $familylist->getResult();

这会得到以下结果:

Array
(
    [0] => Array
        (
            [id] => 4
            [surname] => Kentucky
            [firstName] => John
            [email] => email@somewhere.com
            [phone] => 0123 456 7890
            [memID] => 2
            [memFirstName] => Jason
            [memSurname] => Kentucky
        )

    [1] => Array
        (
            [id] => 4
            [surname] => Kentucky
            [firstName] => John
            [email] => email@somewhere.com
            [phone] => 0123 456 7890
            [memID] => 3
            [memFirstName] => Michael
            [memSurname] => Kentucky
        )

)

但我想要得到的是这样的:

Array
(
    [0] => Array
        (
            [id] => 4
            [surname] => Kentucky
            [firstName] => John
            [email] => email@somewhere.com
            [phone] => 0123 456 7890
            [members] => Array
            (
              [0] => Array
                  (
                    [memID] => 2
                    [memFirstName] => Mick
                    [memSurname] => Burke
                  ),
              [1] => Array
                  (
                    [memID] => 3
                    [memFirstName] => John
                    [memSurname] => Burke
                  )
            )

        )
)

我怎么能通过Symfony2来做到这一点?

1 个答案:

答案 0 :(得分:0)

在querybuilder中执行您的操作。

    $qb = $this->getEntityManager()->createQueryBuilder();

    $result = $qb->select('mf, mc')
        ->from('MyBundle:MapFamilies', 'mf')
        ->join('mf.mapContacts', 'mc')
        ->where('mf.centre = :centre')
        ->setParameter('centre', $centre)
        ->getQuery()->getArrayResult();

这将为您提供一个MapFamily数组及其相关的MapContact实体。

我猜测了MapFamily的属性名称 - > MapContact所以你可能需要改变它。