Wellington Avelino
Wellington Avelino

Reputation: 199

Suppress WHERE clause if is passed Zero or Nothing in CakePHP 3.0

I'm working with CakePHP 3.0 and created a query for your ORM, this query is working perfectly but now I need if a particular parameter is 0 or nothing is passed to the method the where clause is deleted.

Method that creates the query to the 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 nothing the where clause should be deleted.

Upvotes: 1

Views: 53

Answers (1)

Leonel Sanches da Silva
Leonel Sanches da Silva

Reputation: 7220

No secret. Just strip the logic like this:

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);
}

Upvotes: 2

Related Questions