Doctrine - or where?

2019-01-27 13:46发布

问题:

I have the following query:

$query = Doctrine_Query::create()
                ->from('Member m')
                    ->where("m.type='1'")
                        ->andWhere("m.name LIKE '%$term%'")
                        ->orWhere("m.surname LIKE '%$term%'")
                        ->orWhere("m.company LIKE '%$term%'")
                        ->orderBy('id DESC');

But it's not working like I want — it is ignoring type column.

What I need is result set where m.type=1 and some of other fields in this query is LIKE 'something'.

回答1:

$query = Doctrine_Query::create()
  ->from('Member m')
  ->where('m.type = 1 AND m.name LIKE ?', '%'.$term.'%')
  ->orWhere('m.type = 1 AND m.surname LIKE ?', '%'.$term.'%')
  ->orWhere('m.type = 1 AND m.company LIKE ?', '%'.$term.'%')
  ->orderBy('m.id DESC');

Your OR conditions didn't include the first condition. It's also recommended to use the ? for your variables to ensure Doctrine escapes them.



回答2:

Tom's answer is correct, although I like to keep code repetition/duplication to a minimum.

This way should also work, while being a shorter, cleaner way to do it

$query = Doctrine_Query::create()
       ->from('Member m')
       ->where('m.type = ?', 1)
       ->andWhere('m.name LIKE :term OR m.surname LIKE :term OR m.company LIKE :term', array(':term' => '%' . $term . '%'))
       ->orderBy('m.id DESC');


标签: php doctrine