4

可能重复:
使用 Zend_Db_Table_Abstract 对 WHERE 子句进行分组

我需要创建这样的东西:

select name from table where active = 1 AND (name LIKE 'bla' OR description LIKE 'bla')

第一部分很简单:

$sqlcmd = $db->select()
->from("table", "name")
->where("active = ?", 1)

现在是棘手的部分。我怎样才能筑巢?我知道我可以写

->orWhere("name LIKE ? OR description LIKE ?", "bla")

但那是错误的,因为我需要动态更改所有部分。查询将在脚本运行时构建。有些部分被删除,有些被改变。在此示例中,我需要添加那些 OR-s,因为有时我需要进行更广泛的搜索。 《我的 Zend Logic》告诉我正确的做法是这样的:

$sqlcmd = $db->select()
->from("table", "name")
->where("active = ?", 1)
->where(array(
    $db->select->where("name LIKE ?", "bla"),
    $db->select->orWhere("description LIKE ?", "bla")
))

但这不起作用(至少我不记得它起作用了)。

。有人可以帮我找到一种面向对象的方式来嵌套“where” -s

4

2 回答 2

1

这是 ZF 手册中的一个示例

  // Build this query:
  //   SELECT product_id, product_name, price
  //   FROM "products"
  //   WHERE (price < 100.00 OR price > 500.00)
  //     AND (product_name = 'Apple')

  $minimumPrice = 100;
  $maximumPrice = 500;
  $prod = 'Apple';

  $select = $db->select()
               ->from('products',
                      array('product_id', 'product_name', 'price'))
               ->where("price < $minimumPrice OR price > $maximumPrice")
               ->where('product_name = ?', $prod);

它应该适合您的需求

于 2010-05-10T12:58:22.907 回答
-3

要构建此查询:

SELECT product_id, product_name, price FROM "products" WHERE (price > 100.00) AND (price < 500.00)

使用此代码:

$minimumPrice = 100;
$maximumPrice = 500;

$select = $db->select()
             ->from('products',
                    array('product_id', 'product_name', 'price'))
             ->where('price > ?', $minimumPrice)
             ->where('price < ?', $maximumPrice);
于 2011-01-01T13:47:11.587 回答