Delete WHERE clause if passed Zero or Cakephp 3.0

Asked

Viewed 42 times

1

I’m working with the CakePHP 3.0 and created a query for his ORM, this query is working perfectly but now I need that if a certain parameter is 0 or nothingness is passed to the class method where 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 for 0 or not even something passed the clasula where should be deleted.

1 answer

1


Not much of a secret. Just segmenting 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);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.