我正在使用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 子句。
答案 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);
}