In Symfony2 and Doctrine I would like to execute a query that returns a count and a group by.
Here's what I've tried. This is the SQL I want to run:
SELECT `terrain_id` , COUNT( * )
FROM `Partie`
WHERE 1 =1
GROUP BY `terrain_id`
With my entity:
class Partie
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\ManyToOne(targetEntity="Gp\UserBundle\Entity\User",
inversedBy="parties", cascade={"persist"})
* @ORM\JoinColumn(nullable=false)
*/
private $user;
/**
* @ORM\ManyToOne(targetEntity="Gp\JeuxBundle\Entity\Terrain")
*/
private $terrain;
This is my PartieRepository
public function getTest(\Gp\UserBundle\Entity\User $user){
return $this->createQueryBuilder('p')
->select('count(p), p.terrain')
->where('p.user = :user')
->setParameter('user', $user)
->groupBy('r.terrain')
->getQuery()
->getResult();
}
This is the error I get:
[Semantical Error] line 0, col 19 near 'terrain FROM': Error:
Invalid PathExpression. Must be a StateFieldPathExpression.
You'll probably want to go with a Native Query
Just add in any having / where clauses as needed.
The following is my result:
The lack of
terrain
in the first array is due to nullterrain_id
.EDIT
OP has unexpected results, so here are some troubleshooting steps:
1) Try a
var_dump($query->getSQL());
right before thereturn
statement, and run the SQL directly against your DB. If this produces incorrect results, examine the query and alter the$sql
as appropriate.2) If #1 produces correct results, try a
var_dump($query->getResult());
right before the return statement. If this produces correct results, something is going on deeper in your code. It's time to look at whyterrain
is being filtered. It may be as simple as removing or changing the alias in SQL andaddScalarResult
.3) Try an even simpler function:
This error occurs on this line :
select('count(p), p.terrain')
where you are trying to usep
alias that doesn't exist anymore. Theselect
method override the default alias of thecreateQueryBuilder()
. To avoid this, useaddSelect
instead or specify clearly thefrom
method. Try this :or this :
How to execute a raw Query with count and group by:
Hook onto your manager and make a new connection:
Create your query and fetchAll:
Get the data out of result like this: