我有两个表,一个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来做到这一点?
答案 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所以你可能需要改变它。