Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write Zend db select with OR condition inside AND condition

Can someone guide me to write a query like below using Zend db select :

SELECT `tbl_md_users`.* 
FROM `tbl_md_users` 
WHERE 
      user_type <> 'TYPE1')
AND (first_name LIKE '%tom%' OR last_name LIKE '%tom%' OR user_name LIKE '%tom%') 
like image 472
user1890970 Avatar asked Dec 17 '12 06:12

user1890970


3 Answers

If you wanted

SELECT `tbl_md_users`.* 
FROM `tbl_md_users` 
WHERE 
  user_type <> 'TYPE1')
AND (first_name LIKE '%tom%' OR first_name LIKE '%dick%' OR first_name LIKE '%harry%')

then the first answer doesn't work

I used Zend_Db_Expr instead

$likeTom = new Zend_Db_Expr("first_name LIKE '%tom%'");
$likeDick = new Zend_Db_Expr("first_name LIKE '%dick%'");
$likeHarry = new Zend_Db_Expr("first_name LIKE '%harry%'");

$query = $database->select ()
    ->from ('tbl_md_users')
    ->where ('user_type <> ?', 'TYPE1')
    ->where ("{$likeTom} OR {$likeDick} OR {$likeHarry}");
like image 149
Simon77 Avatar answered Nov 11 '22 21:11

Simon77


    $query = $database->select ()
        ->from ('tbl_md_users')
        ->where ('user_type <> ?', 'TYPE1')
        ->where ("first_name LIKE '%?%' OR last_name LIKE '%?%' OR user_name LIKE '%?%'", 'tom');
like image 38
akond Avatar answered Nov 11 '22 20:11

akond


The current, up-to-date solution is to call nest() and unnest() in the where clause:

$select->where
    ->nest()
        ->equalTo('column1', 1)
        ->or
        ->equalTo('column2', 2)
    ->unnest()
    ->and
    ->equalTo('column3', 3);
like image 1
Andreas Avatar answered Nov 11 '22 19:11

Andreas