I have this SQL query:
select *
from tblapplicant AS a
WHERE a.napplicantid
not in (
select napplicantid
from tblcontract
where dstart BETWEEN '2011-10-27' AND '2012-01-26'
OR dend BETWEEN '2011-10-27' AND '2012-01-26')
And I want to build this query in Doctrine 1.2:
$Query = Doctrine_Query::create()
->select('a')
->from('tblapplicant a')
->innerJoin('a.tblintermediair i')
->where('i.nintermediairid = ? ', $intermediairid)
->addWhere('a.napplicantid NOT IN (select c.napplicantid from tblcontract c WHERE c.dstart BETWEEN ? AND ? OR c.dend BETWEEN ? AND ?)', array($this->tbljobavailable->getFirst()->dday, $this->tbljobavailable->getLast()->dday, $this->tbljobavailable->getFirst()->dday, $this->tbljobavailable->getLast()->dday));
but somehow it keeps complaining:
Couldn't find class c
Any ideas?
Just had this issue a few days ago.
One of the possible solutions is adding a one to one relation for a tblapplicant table itself. I did not like this one, so just created additional query to get ids for exclusion. In your case that would be like this:
$notIn = Doctrine_Query::create()->(put your subselect query here)->execute(array(), Doctrine_Core::HYDRATE_SINGLE_SCALAR);
$Query = Doctrine_Query::create()
->select('a')
->from('tblapplicant a')
->innerJoin('a.tblintermediair i')
->where('i.nintermediairid = ? ', $intermediairid)
->whereNotIn('a.napplicantid', $notIn);
Related
I am new to Laravel but I would like to create this Query(MySQL):
SELECT
*
FROM
(
SELECT
ce.empresa_id,
CONCAT(ce.nombre, ' ', ce.apellido) AS nombre,
ce.grupo_contable
FROM
cliente_empresa AS ce
UNION
SELECT
cc.empresa_id,
cc.nombre,
cc.grupo_contable
FROM
cuenta_contable AS cc
UNION
SELECT
cci.empresa_id,
cci.grupo_iva AS nombre,
cci.cuenta_contable AS grupo_contable
FROM
cuenta_contables_iva AS cci
) AS cuentasContables
WHERE
cuentasContables.empresa_id = 1
AND (cuentasContables.nombre LIKE '%a%'
OR cuentasContables.grupo_contable LIKE '%%')
Looking at Documentation I can't find the proper way to do it. Thank you.
Normally, for a query that the ORM can't manage, you would probably want to simply call \DB::raw:
$results = \DB::table('users')
->select(\DB::raw(/* your stuff here */))
However in your case, you might want to consider sticking to the ORM. It looks like you might want to try something like:
$first = DB::table('cliente_empresa')
->where('empresa_id', '=', 1);
$second = DB::table('cuenta_contable')
->where('empresa_id', '=', 1);
$results = DB::table('cuenta_contables_iva')
->where('empresa_id', '=', 1)
->union($first)
->union($second)
->get();
Obviously, you'll need to put your SELECT column statements in there as well.
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.
How to delete rows from multiple tables in one query (with left join).
The query:
DELETE `deadline`, `job` FROM `deadline` LEFT JOIN `job` ....
So, I try it like this:
DB::table('deadline', 'job')
->leftJoin('job', 'deadline.id', '=', 'job.deadline_id')
->where('deadline.id', $id)
->delete();
Seems that Laravel doesn't support delete from multiple tables with left join.
Is there a supported way or workaround?
It seems that my way is not possible. So, I did it like this.
$q = 'DELETE deadline, job FROM deadline LEFT JOIN job ...where deadline.id = ?';
$status = \DB::delete($q, array($id));
Documentation: http://laravel.com/docs/database#running-queries
DB::table(DB::raw('deadline, job')) might work. If it doesn't, you'll have to write the SQL manually and call it via DB::statement().
To make laravel allow a join in a delete is simple - you just need to change the compileDelete function in Illuminate\Database\Query\Grammars\Grammar to this:
public function compileDelete(Builder $query)
{
$table = $this->wrapTable($query->from);
$components = implode(' ', array(
is_array($query->joins) ? $this->compileJoins($query, $query->joins) : '',
is_array($query->wheres) ? $this->compileWheres($query, $query->wheres) : '',
is_array($query->limit) ? $this->compilelimit($query, $query->limit) : '',
is_array($query->offset) ? $this->compileOffset($query, $query->offset) : ''
));
return trim("delete $table from $table ".$components);
}
Then ->delete() will work the way you expect it to. I've already added this as a pull request to the laravel framework repo, so hopefully this might be merged into the next version - just have to see.
$query = 'DELETE courses,course_contents FROM courses
INNER JOIN course_contents ON course_contents.course_id = courses.id
WHERE courses.id = ?';
\DB::delete($query, array($id));
I try to use "distinct on" with doctrine but I get the following error:
Error: Expected known function, got 'on'
class Report extends EntityRepository
{
public function findForList() {
$queryBuilder = $this->createQueryBuilder('r');
$queryBuilder->select('distinct on (r.parentId)')
->orderBy('r.parentId')
->orderBy('r.date', 'DESC');
return $queryBuilder->getQuery()->getResult();
}
}
How could I implement the following query?
select distinct on (r.parent_id)
r.parent_id,
r.id,
r.name
from frontend.report r
order by r.parent_id, r.date desc;
Apparently it doesn't seem possible to do this with the query builder. I tried to rewrite my query in different ways:
select * from frontend.report r
where
r.id in (
select distinct
(select r3.id from frontend.report r3
where r3.parent_id = r.parent_id
order by r3.date desc limit 1) AS id
from frontend.report r2);
But doctrine doesn't support LIMIT:
public function findForList() {
$qb3 = $this->_em->createQueryBuilder();
$qb3->select('r3.id')
->from('MyBundle:frontend\report', 'r3')
->where('r3.parentId = r2.parentId')
->orderBy('r3.date', 'DESC')
//->setMaxResults(1)
;
$qb2 = $this->_em->createQueryBuilder();
$qb2->select('(' . $qb3->getDql() . ' LIMIT 1)')
->from('MyBundle:frontend\report', 'r2')
->distinct(); // groupBy('r2.parentId')
$queryBuilder = $this->createQueryBuilder('r');
$queryBuilder->where(
$queryBuilder->expr()->in('rlt.id', $qb2->getDql())
);
return $queryBuilder->getQuery()->getResult();
}
I think the only solution is to use native SQL queries.
This response is for someone that yet looking for the solution in similar cases.
If you need a sample "DISTINCT" you can use:
$queryBuinder->select('parentId')
->distinct('parentId');
but if you want a "DISTINCT ON" you should use Native SQL instead of Query Builder, check out the manual here: Doctrine Native SQL
Just remove the on word :
$queryBuilder->select('distinct r.parentId')
->orderBy('r.parentId')
->orderBy('r.date', 'DESC');
I'm trying to make a simple query with a subquery in a orWhere clause (with Doctrine).
As always, Doctrine tries to rename every aliases and completely destroys the queries...
Here's an example:
$q = Doctrine_Query::create()
->from('Actualite a')
->where('a.categorie_id =?', $id)
->orWhere('a.categorie_id IN (select id from cat.categorie as cat where cat.categorie_id =?)', $id)
->execute();
Which in MySQL would make something like:
SELECT *
FROM actualite a
WHERE a.categorie_id = 1 OR a.categorie_id IN (SELECT cat.id FROM categorie cat WHERE cat.categorie_id = 1);
Everything is right about it, but then again Doctrine destroys it:
Couldn't find class cat
Every time I try to do something a little complex with Doctrine, I have errors with aliases. Any advice or ideas about how to fix this?
Thanks!
The SQL example you've provided is fine but the corresponding Doctrine syntax has a couple of errors. Here's a clean version:
$q = Doctrine_Query::create()
->select('a.*')
->from('Actualite a')
->where('a.categorie_id = ?', $id)
->orWhere('a.categorie_id IN (SELECT cat.id FROM Categorie cat WHERE cat.categorie_id = ?)', $id)
->execute();
You should use createSubquery() to explicitely tell doctrine about your nested subquery. So your query should look something like this:
$q = Doctrine_Query::create()
->select('a.*')
->from('Actualite a')
->where('a.categorie_id = ?', $id)
;
$subquery = $q->createSubquery()
->select("cat.id")
->from("Categorie cat")
->where("cat.categorie_id = ?", $id)
;
$q->orWhere('a.categorie_id IN ('.$subquery->getDql().')')->execute();
Another example can be found here:
http://www.philipphoffmann.de/2012/08/taming-doctrine-subqueries/
I think you query should be like this add the select and remove as
$q = Doctrine_Query::create()
->select('a.id')
->from('Actualite a')
->where('a.categorie_id =?', $id)
->orWhere('a.categorie_id IN (select id from cat.categorie cat where cat.categorie_id =?)', $id)
->execute();
Try this may help you.
Thanks