Symfony Doctrine, select from subquery with join - php

Haven't been able to find a solid solution for this, but I have a mySQL query that I want to translate to Doctrine. It is a select from a subquery with joins and I might have read somewhere that joins are not allowed in subqueries in Doctrine.
Here is the SQL:
SELECT part, SUM(qty) as qty FROM (SELECT part, SUM(qty) as qty FROM sub LEFT JOIN main ON main.id = main_id WHERE hold != 1 GROUP BY name, part) AS tbl GROUP BY part
This is what I tried and it is all wrong.
$em = $this->getDoctrine()->getManager();
$q = $em->createQuery('v');
$q2 = $em->createSubQuery()
->select('m.part, sum(s.qty) qty')
->from('Sub s')
->leftJoin('s.main m')
->where('s.hold != 1')
->groupBy('m.part');
$q->select('m.part, sum(qty)', $q2->getDQL());
One of the first error I got was:
FatalErrorException: Error: Call to undefined method Doctrine\ORM\EntityManager::createSubQuery() in ....Controller.php line 238
I am pretty sure it isn't just this that I'm doing wrong but it is the first thing that's coming up. So getManager() apparently doesn't have a createSubQuery() function? What is the right way to do this?

There's no method like createSubQuery(). Take a look at that answer: https://stackoverflow.com/a/10763358

Related

Getting "Fatal error: Call to a member function fetch_assoc() on a non-object" on SQL query

I have these two tables in my database:
Statements
and Tags
I'm trying to execute this query
SELECT s.id, s.name, s.preview, s.approved FROM Statements s JOIN Tags t ON s.id = t.probID WHERE s.approved = TRUE AND t.tag IN ("Geometry") GROUP BY s.id, s.name, HAVING COUNT(DISTINCT t.tag) = 1,
but getting "Fatal error: Call to a member function fetch_assoc() on a non-object in C:\wamp\www\file.php on line 46", where 46th line is while($row = $res->fetch_assoc()){
Is something wrong with my query?
I suppose you are using MySQLi, correct me if I am wrong.
In the span of time I used it, whenever this kind of problem was presented to me, I had a problem with the query which I was not able to identify before the execution. Given that my query had failed, no SQLStatement object (or whatever its name is) was created. Therefore, no fetch_* method could be called on that!
I believe your problem is a very simple one: you have a trailing comma before your HAVING clause which is messing your query up. I reproduced your SQL structure and query on my PC, and everything worked correctly.
SELECT
s.id, s.name, s.preview, s.approved
FROM
Statements s JOIN Tags t ON s.id = t.probID
WHERE
s.approved = TRUE AND t.tag IN ('Geometry')
GROUP BY s.id, s.name
HAVING COUNT(DISTINCT t.tag) = 1
Try this one out.
Just a note: whenever I have to deal with a true or false in SQL and I am storing it as a *INT UNSIGNED, I feel like using 1 as true and 0 as false never creates any problem, while using TRUE or FALSE sometimes does! This was not the case, anyway :)
If you use var_dump($result); don't use it. Instead of that, put the result in the $result variable. $result = $stmt->get_result();

Issue in Laravel 5.1 Inner Join Query

Below is my Query in Laravel 5.1
\App\Models\Project\Bids\ProjectBid_Model
::selectRaw('B.*')
->join('tblproject P','B.projectid','=','P.projectid')
->where('P.WhoCreatedTheProject',14)
->first()
and below is the equivalant query
select B.* from `tblprojectbid`
inner join `tblproject P` on `B`.`projectid` = `P`.`projectid`
where `P`.`WhoCreatedTheProject` = 14 limit 1
What's the problem ?
Please check the line 1 in Query: select B.* from tblprojectbid.
What's the question ?
How can I change
select B.* from tblprojectbid
to
select B.* from tblprojectbid B
If you want to use Eloquent I'm afraid there is no easy way to do it.
I use in this case full table name for model for instance
\App\Models\Project\Bids\ProjectBid_Model
::selectRaw('bid_table.*')
->join('tblproject AS P','bid_table.projectid','=','P.projectid')
->where('P.WhoCreatedTheProject',14)
->first()
However it's also possible that you set alias in ProjectBid_Model:
protected $table = 'bid_table AS B';
The con is you will have this table always aliased with B, so in case you have 2 models with same alias (in this case B), you won't be able to change it later just for one table, so I think the better is 1st approach (without using alias)
Here is the final solution.
\App\Models\Project\Bids\ProjectBid_Model
::selectRaw('B.*')
->from('tblprojectbid as B')
->join('tblproject as P','B.projectid','=','P.projectid')
->where('P.WhoCreatedTheProject',14)
->first()
try this.
\DB::table('tblprojectbid as B')
->select()
->join('tblproject as P','B.projectid','=','P.projectid')
->where('P.WhoCreatedTheProject',14)
->first()

PHP PDO too slow on SELECT with some joins

I'm having a performace problem with the execution of a select in PHP PDO.
Using a script available here at stackoverflow (Simplest way to profile a PHP script), I identified where the problem IS, but I have not found a solution.
My select that is the problem is:
SELECT REDACAO.ID_REDACAO AS ID_REDACAO,
DATE_FORMAT(REDACAO.DATA,'%d/%m/%Y') AS DATAE,
ALUNO.ID_ALUNO AS ID_ALUNO,
(SELECT IFNULL((DATEDIFF(DATE_ADD((SELECT MAX(DATA) FROM REDACAO WHERE ID_ALUNO = ALUNO.ID_ALUNO AND ID_REDACAO NOT IN (SELECT ID_REDACAO FROM CORRECAO)), INTERVAL 7 DAY), now())),NULL) as DATA FROM REDACAO LIMIT 1) AS ULTIMA,
ALUNO.NOME as ALUNO,
REDACAO.ID_TEMA AS ID_TEMA,
TEMA.TITULO as TEMA,
TEMA.MOTIVACIONAIS AS MOTIVACIONAIS,
REDACAO.TEXTO AS TEXTO,
REDACAO.ID_STATUS AS STATUS,
B.NOTA as NOTA,
B.RCORRIGIDA AS CORRIGIDA,
B.NOTA1,
B.COMENTARIO1,
B.NOTA2,
B.COMENTARIO2,
B.NOTA3,
B.COMENTARIO3,
B.NOTA4,
B.COMENTARIO4,
B.NOTA5,
B.COMENTARIO5,
B.COMENTARIO6,
C.COMENTARIO AS COMENTARIO
FROM REDACAO
LEFT OUTER JOIN (SELECT SUM(CORRECAO.C1+CORRECAO.C2+CORRECAO.C3+CORRECAO.C4+CORRECAO.C5) AS NOTA, RCORRIGIDA AS RCORRIGIDA, CORRECAO.C1 as NOTA1, CORRECAO.COM1 as COMENTARIO1, CORRECAO.C2 as NOTA2, CORRECAO.COM2 as COMENTARIO2, CORRECAO.C3 as NOTA3, CORRECAO.COM3 as COMENTARIO3, CORRECAO.C4 as NOTA4, CORRECAO.COM4 as COMENTARIO4, CORRECAO.C5 as NOTA5, CORRECAO.COM5 as COMENTARIO5, CORRECAO.COMGERAL AS COMENTARIO6, CORRECAO.ID_REDACAO FROM CORRECAO GROUP BY CORRECAO.ID_REDACAO) B
ON B.ID_REDACAO = REDACAO.ID_REDACAO
JOIN ALUNO ON ALUNO.ID_ALUNO = REDACAO.ID_ALUNO
JOIN TEMA ON TEMA.ID_TEMA = REDACAO.ID_TEMA
LEFT OUTER JOIN (SELECT (COUNT(COMENTARIO.ID_COMENTARIO)) AS COMENTARIO, COMENTARIO.ID_REDACAO FROM COMENTARIO GROUP BY COMENTARIO.ID_REDACAO) C
ON C.ID_REDACAO = REDACAO.ID_REDACAO
WHERE REDACAO.ID_PROFESSOR = $CodProfessor
and REDACAO.ID_STATUS != 6
ORDER BY (CASE WHEN REDACAO.ID_STATUS = 4 THEN 1 ELSE 0 END) DESC
I'm using (PDO :: FETCH_ASSOC) to get the data. Some columns respond in less than 1 second and others in more than 20 seconds.
Any idea what could be the problem and how to solve it?
Your query contains following that will slow it down:
many joins
many subselects
select without where
functions like COUNT, isnull, datediff, sum.(some of these may cancel an index)
case when
order by
group by
Depending on your indexes, on how the tables are joined, and on how big are the tables, this will eventually get very slower.
Try using 'explain' command, and simplify the query if possible.
explain output
a good video about explain
PDO is not at fault; the query is complex. And there may be missing indexes.
Turn this into a LEFT JOIN (because IN (SELECT...) optimizes poorly.
AND ID_REDACAO NOT IN ( SELECT ID_REDACAO FROM CORRECAO)
Upgrade to 5.6; it has some improvements.
You have two JOIN ( SELECT ... ). Before 5.6 that would be optimized terribly. Move one of them out into a temp table, to which you add a suitable index.
In one of the subqueries, GROUP BY CORRECAO.ID_REDACAO seems to be unnecessary.
These indexes (or PRIMARY KEYs) are needed:
CORRECAO: (ID_REDACAO)
REDACAO: (ID_REDACAO), (ID_PROFESSOR)
ALUNO: (ID_ALUNO)
TEMA: (ID_TEMA)
COMENTARIO: (ID_REDACAO, ID_COMENTARIO) ("compound index")
If those suggestions do not help enough, come back with SHOW CREATE TABLE for each table.

MySQL query into Code Igniter Active Directory format?

I'm trying to get mysql query into Code Igniter's Active Record syntax but am having a bit of a hard time.
The query is as a result of this question: Multiple mysql ORDER BY's for multidimensional ordering/grouping
I've attempted to format the query myself, have tackled a couple of errors, but am unsure how to progress. I had to add in the get_compiled_select() function to DB_active_rec.php myself and change the _reset_select() from protected to public to get it to run at all.
The suggested query is:
select
t.id,
t.group,
t.date,
t.comlete
from
YourTable t
left join
(select
m.group,
min(m.date) as mindate,
min(t.complete) as groupcomplete
from
YourTable m) mt on mt.group = t.group
order by
coalesce(mt.groupcomplete, t.complete),
coalesce(mt.mindate, t.date),
t.group,
t.complete,
t.date
My translation looks like this (note that there's a 'where' clause not in the original, and that 'date' is actually 'due'):
// Sub query
$this->db->select('m.group, min(m.due) as mindate, min(t.complete) as groupcomplete');
$this->db->from('task m');
$this->db->where('property', $property);
$subquery = $this->db->get_compiled_select();
$this->db->_reset_select();
// Main query
$this->db->select('*');
$this->db->where('property', $property);
$this->db->from('task t');
$this->db->join('($subquery) mt','mt.group = t.group');
$this->db->order_by('coalesce(mt.groupcomplete, t.complete)');
$this->db->order_by('coalesce(mt.mindate, t.due)');
$this->db->order_by('t.group');
$this->db->order_by('t.complete');
$this->db->order_by('t.due');
$query = $this -> db -> get();
// Return
return $query->result();
Unfortunately this is just throwing an error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'mt ON `mt`.`group` = `t`.`group` WHERE `property` = '7' ORDER BY coalesce(mt.gr' at line 3
The query as reported by CI looks like:
SELECT * FROM (`task` t) JOIN ($subquery) mt ON `mt`.`group` = `t`.`group` WHERE `property` = '7' ORDER BY coalesce(mt.groupcomplete, `t`.`complete)`, coalesce(mt.mindate, `t`.`date)`, `t`.`due`, `t`.`complete`, `t`.`date`
Anyone able to lend some advice as to how to get this formatted correctly? My mysql skills are, unfortunately, pretty bare, so this is pushing my abilities. Much of the approach of my translation is from answers on Stack Overflow, as I have no experience combining queries in this way (with the subquery).
The problem (or 'one of the problems') is here:
$this->db->join('($subquery) mt','mt.group = t.group');
You use single quotes, so the variable $subquery doesn't get expanded.
This can also be seen in the query that is outputted by CodeIgniter.
When you have multiple order by statements u separate them by comma like this
$this->db->order_by('coalesce(mt.groupcomplete, t.complete), coalesce(mt.mindate, t.date), t.due, t.complete, t.date');

Symfony 2: INNER JOIN on non related table with doctrine query builder

I'm trying to build a query with the doctrine query builder which joins a non related table like this:
$query = $this->createQueryBuilder('gpr')
->select('gpr, p')
->innerJoin('TPost', 'p')
->where('gpr.contentId = p.contentId')
But this doesn't work. I still get an error:
Error: Identification Variable TPost used in join path expression but was not defined before.
I searched for this error message and everybody answered to use the table alias + attribute like p.someAttribute. But the table I want to join isn't related in the table I start my select from.
As a normal mysql query i would write it like this:
SELECT * FROM t_group_publication_rel gpr
INNER JOIN t_post p
WHERE gpr.content_id = p.content_id
Any ideas what i'm doing wrong?
Today I was working on similar task and remembered that I opened this issue. I don't know since which doctrine version it's working but right now you can easily join the child classes in inheritance mapping. So a query like this is working without any problem:
$query = $this->createQueryBuilder('c')
->select('c')
->leftJoin('MyBundleName:ChildOne', 'co', 'WITH', 'co.id = c.id')
->leftJoin('MyBundleName:ChildTwo', 'ct', 'WITH', 'ct.id = c.id')
->orderBy('c.createdAt', 'DESC')
->where('co.group = :group OR ct.group = :group')
->setParameter('group', $group)
->setMaxResults(20);
I start the query in my parent class which is using inheritance mapping. In my previous post it was a different starting point but the same issue if I remember right.
Because it was a big problem when I started this issue I think it could be also interesting for other people which don't know about it.
Joins between entities without associations were not possible until version 2.4, where you can generate an arbitrary join with the following syntax:
$query = $em->createQuery('SELECT u FROM User u JOIN Blacklist b WITH u.email = b.email');
Reference: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language.html
Want to improve this post? Add citations from reputable sources by editing the post. Posts with unsourced content may be edited or deleted.
$dql = "SELECT
a, md.fisrtName , md.LastName, mj
FROM MembersBundle:Memberdata md
INNER JOIN MembersBundle:Address a WITH md = a.empID
INNER JOIN MembersBundle:Memberjob mj WITH md = mj.memberData
...
WHERE
a.dateOfChange IS NULL
AND WHERE
md.someField = 'SomeValue'";
return $em->createQuery( $dql )->getResult();
A DQL join only works if an association is defined in your mapping. In your case, I'd say it's much easier to do a native query and use ResultSetMapping to populate your objects.

Categories