Use PostgreSQL NOT SIMILAR TO in Symfony Doctrine query builder - php

I am attempting to use PostgreSQL's NOT SIMILAR TO exclude a blacklist from the results of a query,
When I run the query in my repository method below:
$qb = $this->getEntityManager()->createQueryBuilder('p');
$query = $qb
->select('p')
->from('CRMPiccoBundle:Person', 'p')
->where("lower(p.email) not similar to '(" . implode('|', $blacklist) . ")%'")
->getQuery();
return $query->getResult();
I get the following error:
[Doctrine\ORM\Query\QueryException]
SELECT p FROM CRMPiccoBundle:Person p WHERE lower(p.email) not similar to '(abuse#|admin#|billing#|compliance#|devnull#)%'
[Doctrine\ORM\Query\QueryException]
[Syntax Error] line 0, col 94: Error: Expected end of string, got 'to'
However, when I run this query against my local DB with PgAdmin it works.
How can I achieve this with Doctrine using the Symfony Doctrine Query builder (or similar)? I am using PostgreSQL 9.5.5

$qb = $this->getEntityManager()->createQueryBuilder('p');
$select = $qb
->select('p')
->from('CRMPiccoBundle:Person', 'p')
;
foreach ($blacklist as $key => $item) {
$select
->where('lower(p.email) NOT LIKE :key'.$key)
->setParameter('key'.$key, "$item%")
;
}
$query = $select->getQuery();
return $query->getResult();

Related

how to write sub-query in symfony doctrine

Am working on a symfony project with backend developed in doctrine & api-platform framework.I need to fetch some details along with checking a field in another table which will be a status. We use this status for handling something in front end.
I tried:-
$qb = $this->createQueryBuilder('contact');
$qb2=$qb;
$sub_query = $qb2->select('field')
->from('OtherTable','g')
->where("'id= '".$personId."'")
->OrderBy('updated_at', 'DESC')
->setMaxResults(1)
->getQuery()
->getResult();
$qb->select("contact.id,
contact.title,
count (distinct person.id) as
number_of_contacts_with_email',(".$sub_query.") as status")
->leftjoin('contact.people', 'person')
->leftJoin('person.jobs', 'jobs')
->groupBy('contact.id, contact.title');
$query=$qb->getQuery();
$result = $qb->getQuery()->getArrayResult();
return $result;
Am getting this error when executing query.
[Semantical Error] line 0, col 59 near 'OtherTable g': Error: Class 'OtherTable' is not defined.
How to write this sub query here?Is there any solution for this?
You should simply use the DQL of the subquery, as example:
// Don't take the query/result instances
$sub_query = $qb2->select('field')
->from('OtherTable','g')
->where("'id= '".$personId."'")
->OrderBy('updated_at', 'DESC')
->setMaxResults(1);
and use
$qb->select("contact.id,
contact.title,
count (distinct person.id) as
number_of_contacts_with_email',(".$sub_query->getDQL().") as status")
->leftjoin('contact.people', 'person')
->leftJoin('person.jobs', 'jobs')
->groupBy('contact.id, contact.title');
Hope this help

Request to MySQL

I need to execute the following request to the MySQL server from symfony.
SELECT count(DISTINCT hotel_id) FROM symfony.search_result where request_id=#requrst_id
Code:
In controller:
$qwery2=$repository->hotelsCount($searchId);
Function:
public function hotelsCount($requestId){
$qb = $this->createQueryBuilder('self');
$qb->select('count(hotel_id)')
->where('self.request_id=:req_id')
->setParameter('self.req_id',$requestId)->getQuery()->getResult();
$rez=$qb->getQuery()->getSingleScalarResult();
var_dump($rez);
return $rez->fetchAll();
}
But i got error:
[Semantical Error] line 0, col 13 near 'hotel_id) FROM': Error: 'hotel_id' is not defined.
Table:
Use count(self.hotel_id) in your select
or count(self.hotelId). And in your where: self.reqId < check the entitys for that
I'm still new myself, so I admit I didn't completely follow your code, but try single quotes around 'hotel_id'
Try this, in this case, entity name is "SearchResult" and bundle name is "AppBundle", change it if is needed.
public function hotelsCount($requestId) {
$qb = $this->createQueryBuilder();
$qb->select('count(p.hotel_id)');
$qb->from('AppBundle:SearchResult', 't')
->where('p.request_id = :id')
->setParameter('id', $requestId);
$count = $qb->getQuery()->getSingleScalarResult();
return $count;
}

Doctrine2 QueryBuilder Join

So, I'm new to doctrine, and I'm trying to do a basic joint, but I guess I'm missing something, on my entities or I don't know for sure.
Doctrine Repository:
$queryBuilder = $this->createQueryBuilder()
->select('c.*, a.*')
->from('My\Entity\CompanyAdminNotes', 'c')
->innerJoin('Administrators','a','a.id = c.admin_id')
->where('c.admin_id = :admin_id')
->setParameter('admin_id', $id);
return $queryBuilder->getQuery()->getResult();
And I get the following error
Message: [Semantical Error] line 0, col 76 near 'a,
My\Entity\CompanyAdminNotes': Error: Identification Variable
Administrators used in join path expression but was not defined
before.
I'm not sure if my query it's wrong or something else isn't set. Can you guys give me a hint?
try to change this:
->innerJoin('Administrators','a','a.id = c.admin_id')
to this:
->innerJoin('My\Entity\Administrators','a','a.id = c.admin_id')
Because It need the path as you done into the from
UPDATE
Trying another solution like this:
$queryBuilder = $this->createQueryBuilder('c')
->select('c, a')
->from('My\Entity\CompanyAdminNotes', 'c')
->innerJoin('My:Administrators','a','a.id = c.admin_id')
->where('c.admin_id = :admin_id')
->setParameter('admin_id', $id);

Is there any way to "free" the Doctrine2 QueryBuilder object?

I am running into an interesting issue and now I am curious about the "why". Maybe this Doctrine2 related, maybe it's not, maybe is just OOP.
Take a look to the following Doctrine Repository function:
public function generateOrderPush(int $quote_id): array
{
$group_quote_id = $this->getEntityManager()->getRepository('QuoteBundle:Quote')->find($quote_id)->getGroupQuoteId();
$em = $this->getEntityManager();
$qb = $em->createQueryBuilder();
$header = $qb->select(['q.quoteId','q.othersQuoteId','IDENTITY(q.distributor)'])
->from('QuoteBundle:Quote', 'q')
->where('q.quoteType =:quote_type')
->andWhere('q.groupQuoteId =:group_quote_id')
->setParameter('quote_type', 'current')
->setParameter('group_quote_id', $group_quote_id)
->setMaxResults(1)
->orderBy('q.quoteId', 'ASC')
->getQuery()
->getArrayResult();
$details = $qb->select(['qt.quoteId', 'qt.othersQuoteId', 'IDENTITY(qt.customer)'])
->from('QuoteBundle:Quote', 'qt')
->join('QuoteBundle:QuoteDetail', 'qd', 'WITH', 'qt.quoteId = qd.quoteId')
->where('qt.quoteType =:quote_type')
->andWhere('qt.groupQuoteId =:group_quote_id')
->setParameter('quote_type', 'current')
->setParameter('group_quote_id', $group_quote_id)
->groupBy('qd.renewalPartNumber')
->orderBy('qt.quoteId', 'ASC')
->getQuery()
->getArrayResult();
return [];
}
The first query $header is executed properly and I got data back. The second query $details is failing as error below show:
SELECT q0_.quote_id AS quote_id_0, q0_.QuoteID AS QuoteID_1,
q0_.CustomerSiteID AS sclr_2, FROM quote q1_ INNER JOIN quote_detail
q2_ ON (q0_.quote_id = q2_.quote_id), quote q0_ WHERE q0_.quote_type =
? AND q0_.group_quote_id = ? GROUP BY q2_.RenewalPartNumber ORDER BY
q0_.quote_id ASC LIMIT 1' with params ["current", 1428]:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'q0_.quote_id' in
'on clause'
I think somehow Doctrine keep|think I am referring to the first object (from previous) query when I am not since I have added a new alias for the second query qt.
A solution to the issue could be split this into two different functions but before get into that one, I would like to know why is this happening and if there is any other way than mine to fix the problem.
Use a different queryBuilder object:
public function generateOrderPush(int $quote_id): array
{
$group_quote_id = $this->getEntityManager()->getRepository('QuoteBundle:Quote')->find($quote_id)->getGroupQuoteId();
$em = $this->getEntityManager();
$qb = $em->createQueryBuilder();
$anotherQb = $em->createQueryBuilder();
$header = $qb->select(['q.quoteId','q.othersQuoteId','IDENTITY(q.distributor)'])
->from('QuoteBundle:Quote', 'q')
->where('q.quoteType =:quote_type')
->andWhere('q.groupQuoteId =:group_quote_id')
->setParameter('quote_type', 'current')
->setParameter('group_quote_id', $group_quote_id)
->setMaxResults(1)
->orderBy('q.quoteId', 'ASC')
->getQuery()
->getArrayResult();
$details = $anotherQb->select(['qt.quoteId', 'qt.othersQuoteId', 'IDENTITY(qt.customer)'])
->from('QuoteBundle:Quote', 'qt')
->join('QuoteBundle:QuoteDetail', 'qd', 'WITH', 'qt.quoteId = qd.quoteId')
->where('qt.quoteType =:quote_type')
->andWhere('qt.groupQuoteId =:group_quote_id')
->setParameter('quote_type', 'current')
->setParameter('group_quote_id', $group_quote_id)
->groupBy('qd.renewalPartNumber')
->orderBy('qt.quoteId', 'ASC')
->getQuery()
->getArrayResult();
return [];
}

Sent leftjoin querybuilder rsult to twig

i have a leftjoin with doctrine querybuilder
$registros = $this->em->createQueryBuilder();
$registros->select('u,v')
->from('Entity\RegistroCam', 'u')
->leftjoin('Entity\CmMunicipios','v','WITH','u.camMunicipio = v.idMunicipio')
->orderBy('u.camPaterno', 'DESC');
$query = $registros->getQuery();
// Execute Query
$result = $query->getResult();
My problem is when I send the result to twig , it throws the following error
Twig_Error_Runtime: Method "idRegistro" for object "Entity\CmMunicipios" does not exist in "adminPanel.twig.html" at line 87
if i write
$registros->select('u')
works perfectly

Categories