0

I have 2 entities linked by a one to many relation. Recruitment and Candidat You may have many candidats for one recruitment.

I want to list all recruitment and count how many candidat each recruitment has.

I use the recruitment repository and put the code:

public function myFindAllRecruitment() { $qb = $this->createQueryBuilder('r'); $qb->select('r'); $qb->Join('r.candidat', 'c'); $qb->addSelect("COUNT(c.id) as candidatCount"); $qb->groupBy('r.id'); $qb->orderBy('r.id', 'DESC'); return $qb ->getQuery() ->getResult() ; } 

In my RecruitmentController I have:

$listRecruitment = $repository->myFindAllRecruitment(); 

In my TWIG view something like:

{% for recruitment in listRecruitment %} <tr> {#(this is line 48)#}<td>{{ recruitment.id }}</td> <td>{{ recruitment.titleFr }}</td> <td>{{ recruitment.locationFr }}</td>...... 

And I get this error: "Key "id" for array with keys "0, candidatCount" does not exist in MyBundle:Recruitment:index.html.twig at line 48"

If someone knows what wrong with my query it will be nice. Thank you

1
  • Notice that I tried join and leftJoin in the query Commented Jun 18, 2017 at 2:46

2 Answers 2

1

So you have this Candidat entity like this

...... /** * @ORM\ManyToOne(targetEntity="Recruitment", inversedBy="candidates") */ $recruitment; .... 

Then your query should look like this:

 public function myFindAllRecruitment() { $qb = $this->createQueryBuilder('r'); $qb->select('r'); ->addSelect('(SELECT count(c) FROM PATHTO\Bundle\Entity\Candidat as c WHERE c.rectuitment = r.id group by c.rectuitment) as count)'); ->orderBy('r.id', 'DESC'); return $qb->getQuery()->getResult(); } 

you will get output like this:

[ 0 => [ 'rectuitment' => ...Object, 'count'=> ..., ... ] 
Sign up to request clarification or add additional context in comments.

Comments

0

Ok, thank you, I found the solution. It was in the TWIG render:

Objects were accessible with [0] and [1] or ['candidatCount'] for the the count

Code exemple:

{% for recruitment in listRecruitment %} <tr> <td>{{ recruitment[0].id }}</td> <td>{{ recruitment[0].titleFr }}</td> <td>{{ recruitment[0].locationFr }}</td> <td>{{ recruitment[0].typePoste }}</td> <td>{{ recruitment[0].dateins|date('Y-m-d') | localizeddate('full', 'none') }}</td> <td> {{ recruitment['candidatCount'] }}........ 

And the query was good. Thank you

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.