get array output as key value on doctrine querybuilder

Viewed 539

I have two tables for example

student

id name

1  John

2  Doe

subject

id  sub   student
 1  eng    1
 2  maths  1

I have a query as follows on student repository

$this->createQueryBuilder('stud')
                ->select('stud.name,s.sub')
                ->leftJoin('AppBundle:subject', 's', 'WITH', 's.student = stud.id')
                ->getQuery()
                ->getArrayResult();

But I am getting 3 rows with 2 rows as john with different sub and one row as doe. How could I make it two rows with the sub as an array on the result? I am new to query writing. Hope someone could help

Getting output

array:3 [▼
  0 => array:2 [▼
    "name" => John
    "sub" => maths
  ]
  1 => array:2 [▼
    "name" => John
    "sub" => eng
  ]
 2 => array:2 [▼
    "name" => Doe
    "sub" => null
  ]
]

Expecting output

array:2 [▼
  0 => array:2 [▼
    "name" => John
    "sub" => array:2['eng','maths']
  ]
 2 => array:2 [▼
    "name" => Doe
    "sub" => null
  ]
]
1 Answers

The LEFT JOIN returns all records from the left table (here: student), and the matched records from the right table (here: subject). The result is NULL from the right side if there is no match(here: student with id:2).

Here, you should select from subject, then LEFT JOIN it with students. it solves your problem.

Related