Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QueryBuilder Symfony2 Parameters

Hello guys I want to make simple query builder explained below, but I can't change adding string to send them through parameters.

I've like, OpinionRepository:

public function search(array $query)
{
    $qb = $this->_em->createQueryBuilder();

    return $qb
        ->select('o')
        ->from('AppBundle:Opinion', 'o')
        ->join('o.category', 'c')
        ->where('c.id = ?1')
        ->andWhere(
            $qb->expr()->orX(
                $qb->expr()->like('o.title', $qb->expr()->literal('%'.$query['text'].'%')),
                $qb->expr()->like('o.text', $qb->expr()->literal('%'.$query['text'].'%'))
            )
        )
        ->setParameters([
            1 => $query['categoryId']
        ])
        ->getQuery()
        ->getResult()
    ;
}

It's running excellent, but!

I want:

$qb->expr()->like('o.title', $qb->expr()->literal('%'.$query['text'].'%')),

To be:

$qb->expr()->like('o.title', $qb->expr()->literal('%:text%')),

or

$qb->expr()->like('o.title', $qb->expr()->literal('%?2%')),

But error occurs

Too many parameters: the query defines 1 parameters and you bound 2
like image 948
Tomasz Skorupka Avatar asked Aug 04 '26 05:08

Tomasz Skorupka


1 Answers

For parameters binding, DQL pretty much works exactly like PDO .

Try this :

return $qb
    ->select('o')
    ->from('AppBundle:Opinion', 'o')
    ->join('o.category', 'c')
    ->where('c.id = ?1')
    ->andWhere(
        $qb->expr()->orX(
            $qb->expr()->like('o.text', '?2'),
            $qb->expr()->like('o.title', '?2'),
        )
    )
    ->setParameters(array(
        1 => $query['categoryId'],
        2 => '%'.$query['text'].'%',
    ))
    ->getQuery()
    ->getResult()
;
like image 92
chalasr Avatar answered Aug 05 '26 19:08

chalasr



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!