I’m trying to create a query using the LIKE statement. Both examples below work however which one is the better way to go? Is there one that is more secure than the other? Or, performs better? One that conforms to a best practice? Something else? Just wondering here… Also, perhaps there is a totally different way to perform the LIKE operation that I’m unaware of?
Example 1:
$em = $this->getDoctrine()->getEntityManager();
$query = $em->createQuery(
'SELECT u.user1lname FROM MySiteMyBundle:User u WHERE u.user1lname LIKE :searchTerm ORDER BY u.user1lname ASC'
)->setParameter('searchTerm', $searchTerm.'%');
$result = $query->getResult();
Example 2:
$em = $this->getDoctrine()->getEntityManager();
$qb = $em->createQueryBuilder();
$result = $qb->select('n.user1lname')->from('MySite\MyBundle\Entity\User', 'n')
->where($qb->expr()->like('n.user1lname', $qb->expr()->literal($searchTerm.'%')))
->getQuery()
->getResult();
No difference.
All query builder does is to create DQL which is then passed on.
Try looking at:
die($qb->getDQL());
I use query builder because I find it easier than building strings and you can share parts of the query. But the end results will be the same.