2015-11-06 43 views
0

我有點卡在多個where查詢。我想在我的Zend\Db\Sql\Select查詢 '翻譯' 查詢波紋管:Zend Db Sql 選擇多個地方(AND和OR之間的組合)

SELECT `users`.*, `users_metas`.* 
FROM `users` INNER JOIN `users_metas` ON `users`.`ID` = `users_metas`.`parent_id` 
WHERE `role` = 'admin' 
AND ( 
     `users`.`username` like '%q_word%' 
     OR 
     (`users_metas`.`meta_key` = 'name' 
       AND 
      `users_metas`.`meta_value` like '%q_word%') 
    ) 
ORDER BY `date_added` ASC 

我想是這樣的:

$select = new Select(); 
$select->where(array('role' => 'admin')); 
$select->join('users_metas', 'users.ID = users_metas.parent_id'); 

,但我堅持到這個地方:

AND ( 
     `users`.`username` like '%q_word%' 
     OR 
     (`users_metas`.`meta_key` = 'name' 
       AND 
      `users_metas`.`meta_value` like '%q_word%') 
) 

謝謝!

+0

我解決使用'Expresion'查詢,像這樣的'$哪裏= 「users.username LIKE「%」。$搜索。「%」或\t(users_metas.meta_key = '名' AND users_metas.meta_value LIKE'%$ search%'))「; $ select-> where(new Expression($ where));'。但如果有其他方法可以做到這一點,我想嘗試不同的方式。謝謝! – Andreea

回答

0
$where = new Where(); 
$where 
    ->equalTo('role', 'admin') 
    ->nest() 
    ->like('users.username', '%q_word%') 
    ->or 
    ->like('users_metas.meta_key', 'name') 
    ->or 
    ->like('users_metas.meta_value', '%q_word%') 
    ->unnest(); 


$select = new Select(); 
$select 
    ->from('users') 
    ->join('users_metas', 'users.ID = users_metas.parent_id') 
    ->where($where) 
    ->order('date_added');