I am weak with SQL query syntax and i need to make one query with php symfony2.
I have table Company. It have column "city".
I have table CompanyCategory. It have columns "company_id" and "category_id".
I have table Category. It have column "name".
I need to get Total number of categories in all available cities.
Example:
["Riga" => 156,
"Berlin" => 225]
I have looked around for couple of hours but other examples didn't help me enough, because i can't understand such complex queries yet.
I've tried many cases before and now and every time getting different exceptions.
public function getCategoriesInCities() {
return $this->getEntityManager()
->createQuery('SELECT c.city, count(*) as categorycount FROM AdminBundle:Company c INNER JOIN AdminBundle:CompanyCategory s')
->getArrayResult();
}
[Syntax Error] line 0, col -1: Error: Expected Doctrine\ORM\Query\Lexer::T_WITH, got end of string.
Other case:
public function getCategoriesInCities() {
return $asData = $this->getEntityManager()
->createQuery('SELECT c.city, count(*) as categorycount FROM AdminBundle:Company c INNER JOIN AdminBundle:CompanyCategory s ON(c.id = s.company_id) GROUP BY c.city')
->getArrayResult();
}
[Syntax Error] line 0, col 123: Error: Expected Doctrine\ORM\Query\Lexer::T_WITH, got 'ON'
Other case:
public function getCategoriesInCities() {
return $this->createQueryBuilder('c')
->select('c.city, COUNT(*) as categorycount')
->innerJoin('AdminBundle:CompanyCategory ON(c.id = cc.company_id)', 'cc')
->groupBy('c.city')
->getQuery()
->getArrayResult();
}
[Syntax Error] line 0, col 138: Error: Expected Literal, got 'BY'
etc.. can't find out how to solve this.
Its a simple JOIN query..
SELECT t.city,count(*) as categoryCount
FROM Company t
INNER JOIN CompanyCategory s ON(t.id = s.company_ID)
GROUP BY t.city
You are not new to this site, so in the future, at least try to show some attempts and efforts that you did on your own.
Related
How can I convert below query to Doctrine:
SELECT restaurants.restaurant_name ,
restaurants.restaurant_id,
j.LASTPRICE
FROM restaurants
LEFT JOIN
(
SELECT f.food_id AS fid,
f.restaurants_restaurant_id AS rid,
Max(f.food_last_price) AS LASTPRICE
FROM foods AS f
LEFT JOIN restaurants AS r
ON r.restaurant_id = f.restaurants_restaurant_id
WHERE f.food_last_price IS NOT NULL
GROUP BY r.restaurant_id) j
ON restaurants.restaurant_id = j.rid
Here is my code:
$qb = $this->_em->createQueryBuilder();
$qb2 = $this->_em->createQueryBuilder();
$getMaxPercentage = $qb2
->select(
'MAX (Food.foodLastPrice) AS LASTPRICE ',
'Food.foodId AS fId',
'Food.restaurantsRestaurantId AS rID'
)
->from($this->entityClass,'Restaurant')
->innerJoin('Restaurant.foods','Food')
->where('Food.foodLastPrice IS NOT NULL')
->groupBy('Restaurant.restaurantId')
->getDQL();
$restaurantList = $qb
->select('Restaurants.restaurantName, Restaurants.restaurantId , j.LASTPRICE')
->from($this->entityClass,'Restaurants')
->leftJoin($getMaxPercentage,'j','WITH','Restaurants.restaurantId = j.rID')
->getQuery()->execute();
dd($restaurantList);
I give an error :
SELECT Restaurants.restaurantName,': Error: Class 'SELECT' is not defined.
I've already known I could set sub queries in main query, Although in this case I does not want to use sub query in Where expression. Any suggestion for using select in LeftJoin in doctrine?
EDITED : I've tried to use DQL in my query:
$query = $this->_em->createQuery(
'
SELECT Restaurants.restaurantName , Restaurants.restaurantId
FROM App\\Restaurant AS Restaurants
LEFT JOIN (
SELECT f.foodId AS fid,
f.restaurantsRestaurantId AS rid,
Max(f.foodLastPrice) AS LASTPRICE
FROM App\\Food AS f
LEFT JOIN App\\Restaurant AS r
WITH r.restaurantId = f.restaurantsRestaurantId
GROUP BY r.restaurantId) AS J
ON Restaurants.restaurantId = j.rid
');
But I gave an another error :
[Semantical Error] Error: Class '(' is not defined.
Is it possible to use select in left join in Doctrine?
EDITED 2 : I read a similar question and I've decided to write in another way :
$qb = $this->_em->createQueryBuilder();
$qb2 = $this->_em->createQueryBuilder();
$subSelect = $qb2
->select(
array(
'Food.foodLastPrice AS LASTPRICE ',
'Food.foodId AS fId',
'Food.restaurantsRestaurantId AS rId')
)
->from($this->entityClass,'Restaurant')
->innerJoin('Restaurant.foods','Food')
->where('Food.foodLastPrice IS NOT NULL')
->groupBy('Restaurant.restaurantId')
->getQuery()->getSQL();
$restaurantList =
$qb->select(
'Restaurant1'
)
->from($this->entityClass, 'Restaurant1')
->leftJoin('Restaurant1',sprintf('(%s)',$subSelect),'internalQuery','Restaurant1.restaurantId = internalQuery.rId')
->getQuery()->getSQL();
dd($restaurantList);
Again, I got an error:
near 'Restaurant1 (SELECT': Error: Class 'Restaurant1' is not defined.
What you're trying to do is impossible :
https://github.com/doctrine/doctrine2/issues/3542 (november 2013, but doctrine concept didn't change since and doctrinebot closed this on 7 Dec 2015)
DQL is about querying objects. Supporting subselects in the FROM
clause means that the DQL parser is not able to build the result set
mapping anymore (as the fields returned by the subquery may not match
the object anymore). This is why it cannot be supported (supporting it
only for the case you run the query without the hydration is a no-go
IMO as it would mean that the query parsing needs to be dependant of
the execution mode).
In your case, the best solution is probably to run a SQL query instead
(as you are getting a scalar, you don't need the ORM hydration anyway)
You can find workarounds like raw sql, or rethinking your query.
I have below sql query running fine,
SELECT completed_by, count(*) AS Total
FROM tasks
WHERE completed_by is not null AND status = 1
GROUP BY completed_by
;
Em am doing it with doctrine query builder, but not working returning an error.
$parameters = array(
'status' => 1,
);
$qb = $repository->createQueryBuilder('log');
$query = $qb
->select(' log.completedBy, COUNT(log) AS Total')
->where('log.Status = :status')
->groupBy('log.completedBy')
->setParameters($parameters)
->getQuery();
and getting below error;
[Semantical Error] line 0, col 21 near 'completedBy,': Error: Invalid
PathExpression. Must be a StateFieldPathExpression.
I know this answer can be late, but I struggled with the exact same problem, and did not find any answer on the internet, and I believe a lot of people will struggle in this same issue.
I'm assuming your "completedBy" refers to another entity.
So, inside your repository, you can write:
$query = $this->createQueryBuilder("log")
->select("completer.id, count(completer)")
->join("log.completedBy", "completer")
->where('log.Status = :status')
->groupBy("completer")
->setParameters($parameters)
->getQuery();
This will compile to something like:
SELECT completer.id, count(completer) FROM "YOUR LOG CLASS" log INNER JOIN log.completedBy completer WHERE log.Status=:status GROUP BY completer
Now, You can do another query to get those 'completers', by their ids.
This is wrong: COUNT(log) AS Total. It should be something like COUNT(log.log) AS Total.
When you want to select a column who is a fk for another table (entity), use the IDENTITY function instead of the column name only.
Example: In your case
$parameters = array(
'status' => 1,
);
$qb = $repository->createQueryBuilder('log');
$query = $qb
->select('IDENTITY(log.completedBy), COUNT(log.something) AS Total')
->where('log.Status = :status')
->groupBy('log.completedBy')
->setParameters($parameters)
->getQuery();
iam trying to join multiple tables in my bundle using DQL and
Error:
[Syntax Error] line 0, col 610: Error: Expected =, <, <=, <>, >, >=, !=, got 'CarparkFueltext'
Entity:
https://gist.github.com/anonymous/9fc7bfe89bb54427f89c
Code:
https://gist.github.com/anonymous/63680019a3f260733dca
I have also tried with createQueryBuilder() method
Code:
https://gist.github.com/anonymous/92012697fc99fcf02da5
ERROR:
[Syntax Error] line 0, col 423: Error: Expected Literal, got 'JOIN'
However if i remove either of the join statements
JOIN MyBundle:SpareParts\CarparkAgestext CarparkAgestext
OR
JOIN MyBundle:SpareParts\CarFueltext CarFueltext
I am getting the data.
The error seems to be that I cannt join multiple tables and i need to join atleast 5 tables to it. Any Idea how can i acheive it.
Join syntax is here.
General example:
...
->select(['e1'])
->from('AcmeDemoBundle:Entity1', 'e1')
->innerJoin('AcmeDemoBundle:Entity2', 'e2', 'WITH', 'e2.e1 = e1')
->innerJoin('AcmeDemoBundle:Entity3', 'e3', 'WITH', 'e3.e2 = e2')
...
You can join multiple tables, but you need to use the right association of MyBundle:SpareParts\Carparktype.
You should use a query like the following one:
$query = $this->getEntityManager()->createQueryBuilder()
->select($fields)
->from('MyBundle:SpareParts\Carparktype Carparktype')
->innerJoin('Carparktype.agesText CarparkAgestext')
->where('Carparktype.makename =:makename')
->andWhere('CarparkAgestext.id =:agesid')
->setParameter('makename',$makename)
->setParameter('agesid',$param)
->getQuery()
->getResult();
As you see you will build a JOIN statement starting from a single property of SpareParts\Carparktype, which will be mapped as an association (a foreign key) for SpareParts\CarparkAgestext.
Maybe you're trying to JOIN two tables with no relationship defined. If that's the case you can JOIN them using WITH
FROM FooBundle:Entity1 e1 JOIN FooBundle:Entity2 e2 WITH e2.e1_id = e1.id
I want to use an inner Join for my tables auto and rent('s'). Its an 1:N relationship. If I use ->innerJoin('s', 'a') it comes to some errors like this:
[Semantical Error] line 0, col 62 near 's a, ChrisKfzBuchungBundle:Auto': Error: Class 's' is not defined.
$repo = $this->getDoctrine()->getRepository('ChrisKfzBuchungBundle:Rent');
$qb = $repo->createQueryBuilder('s');
$qb->from('ChrisKfzBuchungBundle:Auto', 'a')
->where('s.mieteStart >= :date_from')
->andWhere('s.mieteEnde <= :date_to')
->setParameter('date_from', $date_from)
->setParameter('date_to', $date_to);
How do I join one ore more tables with queryBuilder?
There are methods for that and also for me it just worked with a configured relation between the two entites. Here are two working examples:
left join:
$query = $repo->createQueryBuilder('s')
->leftJoin(ChrisKfzBuchungBundle:Auto', 'a', 'WITH', 's.id = a.yourJoinCOlumn')
...
inner join:
$query = $repo->createQueryBuilder('s')
->select('s, a')
->innerJoin('s.yourJoinColumn', 'a')
...
In Symfony2, I have a many:many relationship between users and roles.
I am trying to get a list of all the users which are not linked to the ROLE_SUPER_ADMIN role.
Before migrating to Symfony2/Doctrine, I had achieved this with a simple NOT IN sql query, but for the life of me I can't achieve the same effect with doctrine.
Here is what I am trying:
$em = $this->getDoctrine()->getManager();
$qb = $em->createQueryBuilder();
$qb2 = $qb;
$dql = $qb->select('sa.id')
->from('AcmeAdminBundle:User', 'sa')
->leftJoin('sa.roles', 'r')
->andWhere('r.role = :role')
->getDQL();
$result = $qb2->select('u')
->from('AcmeAdminBundle:User', 'u')
->where($qb2->expr()->notIn('u.id', $dql))
->setParameter('role', 'ROLE_SUPER_ADMIN')
$users = $result->getQuery()->getResult();
But this is the error:
[Semantical Error] line 0, col 140 near 'sa LEFT JOIN':
Error: 'sa' is already defined.
And this is the output:
SELECT u
FROM AcmeAdminBundle:User sa
LEFT JOIN sa.roles r, AcmeAdminBundle:User u
WHERE u.id NOT IN (
SELECT sa.id
FROM AcmeAdminBundle:User sa
LEFT JOIN sa.roles r
WHERE r.role = :role
)
No idea why it is outputting like that as it should not be performing LEFT JOIN two times, my suspicion is that it has something to do with having two QueryBuilder instances, but could be something else entirely.
You need the MEMBER OF or in your case NOT MEMBER OF option.
$qb->select('sa.id')
->from('AcmeAdminBundle:User', 'sa')
->where(":Role NOT MEMBER OF sa.roles")
->setParameter("Role", <<ROLE_ID_OR_ROLE_ENTITY>>);
I didn't test this code, but it should give you some idea.
Full documentation can be found at http://docs.doctrine-project.org/en/latest/reference/dql-doctrine-query-language.html