Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 653
PrimuS Avatar asked Jan 28 '26 22:01

PrimuS


1 Answers

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();
like image 65
Denis Alimov Avatar answered Jan 31 '26 11:01

Denis Alimov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!