Suppress WHERE clause if passed Zero or Nothing CakePHP 3.0

1

I'm working with CakePHP 3.0 and I've created a query for its ORM , this query is working perfectly however I now need that if a certain parameter is 0 or nothing is passed to the method the class where is suppressed.

Method that creates query for 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;
    }

If $ subCategoryId is 0 or not even something be passed the class where should be suppressed.

    
asked by anonymous 30.07.2015 / 15:33

1 answer

1

There is not much secret. Only segment logic:

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);
}
    
30.07.2015 / 16:21