How to make a query_builder out of raw sql - php

I need help to change this code into a query builder in Symfony 5.
$em = $this->getEntityManager();
$query = "SELECT * FROM fizuser where roles::text LIKE :role";
$statement = $em->getConnection()->prepare($query);
$statement->bindValue('role', '%'.$role.'%');
$statement->execute();
$result = $statement->fetchAll();
return $result;
This is what I've tried:
function (UserRepository $er) {
return $er->createQueryBuilder('u')
->where("u.roles :: text like '%a%'");
However, I can't use "::" tag.

You can do it with -
return $this->createQueryBuilder('u')
->andWhere('u.roles LIKE :role')
->setParameter('role', '%'.'a'.'%')
->getQuery()
->getResult();

I'd like to add some details,
the column type in psql is json.
Using this type of query builder gives me error
SQLSTATE[42883]: Undefined function: 7 ERROR: operator does not exist: json ~~ unknown
LINE 1: ...ted AS activated_25 FROM fizuser f0_ WHERE f0_.roles LIKE $1

Related

Doctrine Query Builder Substring

Hi i got following line:
$query = $qb->select($qb->expr()->substring("p.website",1,$qb->expr()->length("p.website")-4))
->from("AppBundle\Entity\Image" ,"p")
->getQuery();
and got following Exception:
Notice: Object of class Doctrine\ORM\Query\Expr\Func could not be converted to int
I understand why this Exception is thrown but how is it possible to get a substring based on the string size with Query Builder?
OK got it...
The expression $qb->expr()->length("p.website") is first converted into LENGTH("p.website")
So the -4 has to concat as string.
$qb->expr()->length("p.website") **.'-4'**
$query = $qb->select($qb->expr()->substring("p.website",1,$qb->expr()->length("p.website").'-4))
->from("AppBundle\Entity\Image" ,"p")
->getQuery();
In your EntityRepository:
public function getAll()
{
$qb = $this->createQueryBuilder('p');
$query = $qb
->select($qb->expr()->substring("p.website", 1, $qb->expr()->length("p.website").'-4'))
->getQuery();
return $query->getResult();
}

Doctrine where if empty

$repository = $this->getEntityManager()->getRepository('App\Entity\HolidayPackages');
$holiday_packages = $repository
->createQueryBuilder('hp')
->addSelect('hpt')
->innerJoin('hp.holiday_packages_translation', 'hpt')
->where('hpt.code = :code')
->setParameter('code', $language_code)
->andWhere('hpt.title LIKE :title')
->setParameter('title', $title . '%');
if (!empty($starting_date)) {
$repository
->andWhere('hp.starting_date = :starting_date')
->setParameter('starting_date', $starting_date);
}
$repository
->setFirstResult($offset)
->setMaxResults($limit)
->getQuery()
->getResult();
I am trying to filter search. How can i check if parameter is empty, don' t add to where query ?
I followed this link : doctrine2 - querybuilder, empty parameters
But i doesn't works for me.
When i try to like that, i got an error :
Undefined method 'setFirstResult'. The method name must start with either findBy or findOneBy!
Thanks in advice..
Update
if i add to command line setFirstResult error change :
Undefined method 'getQuery'. The method name must start with either findBy or findOneBy!
When i used to use pdo, i can like this using bind parameters. But i don't know how to do in Doctrine.
You should keep using $holiday_packages instead of $repository.
$repository = $this->getEntityManager()->getRepository('App\Entity\HolidayPackages');
$holiday_packages = $repository
->createQueryBuilder('hp')
->addSelect('hpt')
->innerJoin('hp.holiday_packages_translation', 'hpt')
->where('hpt.code = :code')
->setParameter('code', $language_code)
->andWhere('hpt.title LIKE :title')
->setParameter('title', $title . '%');
if (!empty($starting_date)) {
$holiday_packages->andWhere('hp.starting_date = :starting_date')
->setParameter('starting_date', $starting_date);
}
$holiday_packages->setFirstResult($offset)
->setMaxResults($limit)
->getQuery()
->getResult();

How to apply Mysql AND/OR clause in Laravel

I am trying to make a MySQL query inside Laravel.
> "select * from users u where (name like
> '%".$request->search_string."%' or email like
> '%".$request->search_string."%') and (user_type=2)";
I tried the code below
public function searchUsers(Request $request){
$query = DB::table('users as u');
$query->where('u.user_type',2);
$query->where(function($query,$request){
$query->orwhere('u.name','LIKE','%'.$request->search_string.'%');
$query->orwhere('u.email','LIKE','%'.$request->search_string.'%');
});
$result['all_users'] = $query->get();
return Response::json($result);
}
But I am getting the following error
Missing argument 2 for
App\Http\Controllers\PatientController::App\Http\Controllers{closure}()
You have syntax error in where clause. See this:
public function searchUsers(Request $request){
$query = DB::table('users as u');
$query->where('u.user_type',2);
$query->where(function($query)use($request){ // Here is the change
// ^^ Pass only one parameter to closure function and pass `$request` in `use` function
$query->orwhere('u.name','LIKE','%'.$request->search_string.'%');
$query->orwhere('u.email','LIKE','%'.$request->search_string.'%');
});
$result['all_users'] = $query->get();
return Response::json($result);
}

Prioritize MySQL SELECT/LIKE result in Repository

I want to create a query that values more precise search terms, e.g. search for "Essen" should return Essen currently it returns Evessen as this is a valid value as well.
My current function:
public function findCities($city){
$qb = $this->createQueryBuilder('z');
$qb
->select('z')
->where($qb->expr()->like('z.city', ':city'))
->orderBy('z.code')
->setParameter('city', '%'.$city . '%');
return $qb->getQuery()->getResult();
}
Based on THIS advice I created a repository function:
public function findCities($city){
$qb = $this->createQueryBuilder('z');
$qb
->select('z')
->where($qb->expr()->like('z.city', ':city'))
->orderBy('INSTR(z.city, '.$city.'), z.city')
->setParameter('city', '%'.$city . '%');
return $qb->getQuery()->getResult();
}
Unfortunately it returns [Syntax Error] line 0, col 70: Error: Expected known function, got 'INSTR'
Any other approach (that does NOT return an array, as there is a function that needs heavy altering if the output is an array, I'd like to avoid that) maybe?
There is no INSTR function in DQL, that's why you get this error see docs
instead you can make NativeQuery see docs
something like this
$rsm = new \Doctrine\ORM\Query\ResultSetMapping();
$rsm->addEntityResult('City', 'c');
// for every selected field you should do this
$rsm->addFieldResult('c', 'id', 'id');
$rsm->addFieldResult('c', 'name', 'name');
$em = $this->getEntityManager()
->createNativeQuery('
SELECT
id, name
FROM cities WHERE city LIKE '%:city%'
ORDER BY INSTR(city, ':city'), city',
$rsm
)->setParameter('city', $city);
return $em->getResult();

How to select distinct query using symfony2 doctrine query builder?

I have this symfony code where it retrieves all the categories related to a blog section on my project:
$category = $catrep->createQueryBuilder('cc')
->Where('cc.contenttype = :type')
->setParameter('type', 'blogarticle')
->getQuery();
$categories = $category->getResult();
This works, but the query includes duplicates:
Test Content
Business
Test Content
I want to use the DISTINCT command in my query. The only examples I have seen require me to write raw SQL. I want to avoid this as much as possible as I am trying to keep all of my code the same so they all use the QueryBuilder feature supplied by Symfony2/Doctrine.
I tried adding distinct() to my query like this:
$category = $catrep->createQueryBuilder('cc')
->Where('cc.contenttype = :type')
->setParameter('type', 'blogarticle')
->distinct('cc.categoryid')
->getQuery();
$categories = $category->getResult();
But it results in the following error:
Fatal error: Call to undefined method Doctrine\ORM\QueryBuilder::distinct()
How do I tell symfony to select distinct?
This works:
$category = $catrep->createQueryBuilder('cc')
->select('cc.categoryid')
->where('cc.contenttype = :type')
->setParameter('type', 'blogarticle')
->distinct()
->getQuery();
$categories = $category->getResult();
Edit for Symfony 3 & 4.
You should use ->groupBy('cc.categoryid') instead of ->distinct()
If you use the "select()" statement, you can do this:
$category = $catrep->createQueryBuilder('cc')
->select('DISTINCT cc.contenttype')
->Where('cc.contenttype = :type')
->setParameter('type', 'blogarticle')
->getQuery();
$categories = $category->getResult();
you could write
select DISTINCT f from t;
as
select f from t group by f;
thing is, I am just currently myself getting into Doctrine, so I cannot give you a real answer. but you could as shown above, simulate a distinct with group by and transform that into Doctrine. if you want add further filtering then use HAVING after group by.
Just open your repository file and add this new function, then call it inside your controller:
public function distinctCategories(){
return $this->createQueryBuilder('cc')
->where('cc.contenttype = :type')
->setParameter('type', 'blogarticle')
->groupBy('cc.blogarticle')
->getQuery()
->getResult()
;
}
Then within your controller:
public function index(YourRepository $repo)
{
$distinctCategories = $repo->distinctCategories();
return $this->render('your_twig_file.html.twig', [
'distinctCategories' => $distinctCategories
]);
}
Good luck!

Categories