Doctrine 2 Order By Count with join for Symfony 2 Pagerfanta - php

I'm using Symfony2 with Doctrine 2 and i'm creating a Query for the Pagerfanta Bundle for Symfony 2.
The Query is the following:
$qb = $this->createQueryBuilder('t')
->select()
->join('t.pois', 'p');
$qb->groupBy('t.id');
$qb->addOrderBy('count(case when p.image = 1 then 1 else null end)', 'DESC');
Which will give out the following Query:
SELECT t FROM Bundle\Entity\Turn t INNER JOIN t.pois p GROUP BY t.id ORDER BY count(case when p.image = 1 then 1 else null end) DESC
I also created a MySQL Query first so i can rebuild it in Doctrine 2 which looks like this:
SELECT *
FROM `turn`
LEFT JOIN (
poi
) ON ( turn.id = poi.turn_id )
GROUP BY turn.id
ORDER BY count( case when poi.image = 1 then 1 else null end) DESC;
This native Query works perfectly fine, tested in phpmyadmin.
But the Doctrine 2 Query throwes this exeptions:
Twig_Error_Runtime: An exception has been thrown during the rendering of a template ("[Syntax Error] line 0, col 115: Error: Expected end of string, got '('") in Bundle:Admin:showTurnsFiltered.html.twig at line 64.
QueryException: [Syntax Error] line 0, col 115: Error: Expected end of string, got '('
What am i doing wrong? Or is the Pagerfanta bundle not able to work with this Query?

I fixed this by adding a column to the turn Entity (count_poi) and filling it via native SQL.
After that the Query is the following:
SELECT *
FROM `turn`
ORDER BY t.count_poi DESC;
BUT it's just a workaround, i'm not happy with it, but it works for now

Related

New version of php/mysql got an aggregate error in GROUP BY clause

I've got an error on my code saying "Invalid in the select list because it is not contained/ aggregate in the group by clause" like that. This error seems familiar to me in "MS SQL Server". I haven't encountered this error before in MySQL. This error came up when I upgraded my Php version to 7. All my previous web-based program before were affected
I tried to add more column in my "group by" clause, the error got away but the output is not what I am expected. The code below is my old code.
SELECT SUM(s.pscore) as towtal, s.pscore AS totalScore, s.cri_id,
c.can_id, c.canid,c.can_name FROM score s INNER JOIN candidate c ON
s.can_id = c.can_id WHERE cat_id=1 AND s.cri_id = '".$rows['cri_id']."'
AND c.can_sex = 'Female' AND c.can_id='".$kert[$i]."'
GROUP BY s.can_id ORDER BY s.can_id ASC LIMIT 5
When I add GROUP BY s.can_id, s.pscore there will be no errors, but the output is not what I am expected
go to your database and in sql run this command
set GLOBAL sql_mode='';
SET sql_mode=(SELECT REPLACE(##sql_mode, 'ONLY_FULL_GROUP_BY', ''));
An example of a valid query:
SELECT SUM(s.pscore) as towtal
, s.pscore AS totalScore
, s.cri_id
, c.can_id
, c.canid
, c.can_name
FROM score s
JOIN candidate c
ON s.can_id = c.can_id
WHERE cat_id = 1
AND s.cri_id = '".$rows['cri_id']."'
AND c.can_sex = 'Female'
AND c.can_id = '".$kert[$i]."'
GROUP
BY s.pscore
, s.cri_id
, c.can_id
, c.canid
, c.can_name
ORDER
BY s.can_id ASC
LIMIT 5;
Note that this query is vulnerable to injection

Wrong SQL query generated by Doctrine2 Paginator

My scripts stop working after I've upgraded from Doctrine 2.3.6 up to Doctrine 2.5.0 .
I want to perform query with pagination on joined tables. I have two entities: Program and ProgramVersion joined by Program::versions field.
Here is the query:
$query = $em->createQuery('
SELECT m, v
FROM Entity\Program m
LEFT JOIN m.versions v
WITH m.version = v.version
WHERE m.deletedDate IS NULL
ORDER BY m.type asc');
Then I pass the query to Paginator
$pResult = new \Doctrine\ORM\Tools\Pagination\Paginator($query, true);
At the stage when I do $pResult->getIterator() I get the following error message:
An exception occurred while executing '
SELECT DISTINCT id_0
FROM (
SELECT e0_.id AS id_0, e1_.id AS id_27 /* removed a lot of fields here */ FROM entity_program e0_
LEFT JOIN entity_program_version e1_ ON e0_.id = e1_.master_id AND (e0_.version = e1_.version)
WHERE e0_.deleted_date IS NULL
) dctrn_result ORDER BY e0_.type_id ASC':
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'e0_.type_id' in 'order clause'
Obviously the SQL is wrong. The ORDER BY clause is outside of the main SELECT and it contains the field which doesn't exist.
Can anybody help me to solve the issue?

#1241 - Operand should contain 1 column(s): why?

i want use a subquery in a main query like following:
SELECT distinct(cnt.crid),cu.companyName,m.*,cnt.*,m.submitDate as mSubmitDate
from tbl_mahmoleh m,tbl_customer cu,tbl_cntreserve cnt
where m.cuID=cu.cuID and m.mBLID=cnt.mBLID and m.cuID='12'
and (cnt.crID IN (SELECT DISTINCT(crID) FROM tbl_paymentcnt))
and (cnt.crID IN (SELECT pc.crID, SUM( amount ) AS PaySum
FROM tbl_paymentcnt pc GROUP BY pc.crID HAVING PaySum < '2000'))
ORDER BY inputDateD
but i faced by this error
Blockquote #1241 - Operand should contain 1 column(s)
i got it, the IN clause can't work with more than one field, i changed my Query to the following and my Problem was solved.
SELECT DISTINCT(cnt.crid),cu.companyName,m.*,cnt.*,m.submitDate AS mSubmitDate
FROM tbl_mahmoleh m,tbl_customer cu,tbl_cntreserve cnt
WHERE m.cuID=cu.cuID AND m.mBLID = cnt.mBLID AND m.cuID = '12'
AND (cnt.crID IN (SELECT DISTINCT(crID) FROM tbl_paymentcnt))
AND (cnt.crID IN (SELECT pc.crID FROM tbl_paymentcnt pc GROUP BY pc.crID HAVING SUM(amount) < '2500'))
ORDER BY inputDateD

SF2 - Doctrine DQL - Select several columns

I have a table Item with the following columns:
Id
Category
value
date
I build a SQL request which returns all the lines with the latest date for each category:
SELECT *
FROM item i
WHERE (i.category, i.date) IN (SELECT category, MAX(date)
FROM item
GROUP BY category)
This works fine and returns what I need.
I work with Symfony2 and Doctrine, so I would prefer to use DQL (or even better: the QueryBuilder) instead of NativeSQL.
So here is my DQL request :
SELECT i
FROM MyBundle:Item i
WHERE (i.category, i.date) IN (SELECT i2.category, MAX(i2.date)
FROM MyBundle:Item i2
GROUP BY i2.category
)
Which gives me the error:
QueryException: [Syntax Error] line 0, col 103: Error: Expected Doctrine\ORM\Query\Lexer::T_CLOSE_PARENTHESIS, got ','
If I remove the first couple of parenthesis, I get :
QueryException: [Syntax Error] line 0, col 102: Error: Expected =, <, <=, <>, >, >=, !=, got ','
I thought there was a problem with the WHERE so I tried the following just to see what would happen:
SELECT i
FROM MyBundle:Item i
WHERE i IN (SELECT i2.category, MAX(i2.date)
FROM MyBundle:Item i2
GROUP BY i2.category
)
I get:
QueryException: [Syntax Error] line 0, col 116: Error: Expected Doctrine\ORM\Query\Lexer::T_FROM, got ','
But in the doctrine doc, there is an example with several columns after the SELECT, using this same syntax!
Do you have any idea where does my problem come from?
Thank you!
Regards,
You could use exists:
SELECT
i
FROM
MyBundle:Item i
WHERE
EXISTS (
SELECT i2
FROM MyBundle:Item i2
WHERE i2.category = i.category
GROUP BY i2.category
HAVING MAX(i2.date) = i.date
)
You will need to separate the query's conditional statements; This is because DQL is unable to parse the comma separated field names (i.category, i.date).
SELECT
i
FROM
MyBundle:Item i
WHERE
i.category IN ( (SELECT i2.category FROM MyBundle:Item i2 GROUP BY i2.specy) )
AND
i.date IN ( (SELECT MAX(i2.date) FROM MyBundle:Item i2 GROUP BY i2.specy) )
I would also recommend using parentheses () to wrap any sub queries.

At PHP script MySQL query is returning NULL column

I have this sql query:
SELECT *
FROM products p, products_description pd, products_to_categories c left
join products_sex ps on (c.products_id = ps.products_id),
categories cc
WHERE p.products_id = pd.products_id
and p.products_id = c.products_id
and cc.categories_id = c.categories_id
and p.products_status = 1
and p.products_price >= 15.8333333333
and p.products_price <= 40
and p.products_quantity > 0
and (ps.products_sex = "U" or ps.products_sex is null)
and (c.categories_id = 77 or cc.parent_id = 77)
ORDER BY products_sort_order, p.products_date_added desc, pd.products_name ASC
LIMIT 0, 40
If I execute it at MySQL client (command line or Navicat), I get this result:
products_id | dodavatelia_id ...
2153 | 67 ...
But if I get products by PHP script (with mysql_query and mysql_fetch_assoc), I get:
array (
'products_id' => NULL,
'dodavatelia_id' => '67',
...
);
Why am I getting the products_id NULL?
This might be because you are joining multiple tables that contains column with the same name, here products_id so you retrieve the value of the last column with this name that might be NULL.
You should put an alias for the column you want to retrieve :
SELECT p.products_id AS pPropId, p.* FROM products p, ...
Then in your PHP result you can access your column like this:
$result['pPropId']
More info on the SQL Alias functionality here.
EDIT: Why does it work in the command line and not here?
The SQL query works fine and will return each column of name products_id. The issue is that you use mysql_fetch_assoc() that returns an associative array based on your result. And you can't have multiple values for the same key in the array.
So what it might do internally is set $result['products_id'] = p.products_id but then it does the same for the next column with the same name erasing the previous value. You could use mysql_fetch_row() which does not have this issue.
A good practice is to list the columns you really want to retrieve in your SELECT and not just SELECT *. Then it becomes logical that two columns with the same name need different aliases.

Categories