如果在CakePHP 3.0中传递Zero或Nothing,则禁止WHERE子句

时间:2015-07-30 14:15:57

标签: cakephp cakephp-3.0

我正在使用CakePHP 3.0并为query创建ORM,此query工作正常,但现在我需要一个特定参数 0 传递给删除 where 子句的方法。

为ORM创建查询的方法

public function listProductsByTrend($subCategoryId, $productsQuantity, $column, $order) 
{ 
$products = TableRegistry::get('products'); 
$query = $products->find(); 
$query->select(['product_name', 'quantity', 'sold', 'description', 'price', 'old_price', 'thumbnail']) 
->where(['sub_category_id' => $subCategoryId]) 
->order([$column => $order]) 
->limit($productsQuantity); 
return $query; 
} 

如果$ subCategoryId 0 没有,则应删除 where 子句。

1 个答案:

答案 0 :(得分:2)

不是秘密。只需删除这样的逻辑:

public function listProductsByTrend($subCategoryId, $productsQuantity, $column, $order)
{
    $products = TableRegistry::get('products');
    $query = $products->find();
    $query = $query->select(['product_name', 'quantity', 'sold', 'description', 'price', 'old_price', 'thumbnail']);
    if ($subCategoryId > 0) {
        $query = $query->where(['sub_category_id' => $subCategoryId]);
    }

    return $query->order([$column => $order])->limit($productsQuantity);
}