Zend \ Db \ Sql \选择多个位置(AND和OR之间的组合)

时间:2015-11-06 11:03:05

标签: zend-framework zend-framework2 zend-db zend-db-table

我对多个where的查询有点困惑。我想翻译'我的Zend\Db\Sql\Select查询中的查询:

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%')
)

谢谢!

1 个答案:

答案 0 :(得分: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');