php - 如果字段为空,则在限制参数中设置 fetch all 选项
问题描述
对于我的函数,我想设置 2 个参数,如下所示,并且仅在用户想要使用该参数时设置查询的限制。
public function getNewsByCatId($id, $limit){
$args = array(
'fields' => array(
'news.id',
'news.title',
'news.story',
'news.image',
'news.status',
'news.added_date',
'categories.title AS news_category',
'(SELECT users.full_name FROM users WHERE id = news.added_by) as author',
),
'where' => array(
'news_category' => $id
),
'join' => 'LEFT JOIN categories on news.news_category = categories.id',
'limit' => array(0, $limit);
);
return $this->select($args);
}
如果我没有在函数中传递限制值,应该将什么设置为默认参数值?我可以if else
在函数内部使用条件吗?例子:
public function getNewsByCatId($id, $limit){
$args = array(
'fields' => array(
'news.id',
'news.title',
'news.story',
'news.image',
'news.status',
'news.added_date',
'categories.title AS news_category',
'(SELECT users.full_name FROM users WHERE id = news.added_by) as author',
),
'where' => array(
'news_category' => $id
),
'join' => 'LEFT JOIN categories on news.news_category = categories.id',
);
if ($limit > 0) {
//condition to be applied
} else {
//condition to be applied
}
return $this->select($args);
}
解决方案
轻而易举:
public function getNewsByCatId(int $id, ?int $limit = 10) {
$args = [
// your original argument definition
// do NOT SET LIMIT HERE
];
if ($limit !== null && $limit > 0) {
$args['limit'] = [0, $limit];
}
return $this->select($args);
}
我已经为现代 PHP 格式化了代码。如果您的 PHP 版本不支持类型提示、短数组声明等,请更改代码(或者更好的是,考虑升级您的 PHP 引擎)。
这样您就$limit
可以使用默认客户端,或者它们可以通过null
(或整数 <= 0)来完全禁用限制。
推荐阅读
- sas - If-then-else 在 SAS 中的工作原理
- android - Android - 展开视图的高度和宽度
- android - 在 Android 上使用 Google 身份提供程序进行 Cognito 用户池身份验证
- ios - 当 NSKeyedUnarchiver.unarchivedObject 有 CoreText 问题时 NSAttributedString 的 iOS 13 字体
- c++ - 有人可以举一个使用多个功能的例子吗?
- express - 对 FE 和 BE 上的相同路由使用 createProxyMiddleware,同时避免 CORS
- azure-language-understanding - 关于改进 LUIS 语音识别的具体问题
- javascript - 使用搜索而不是数据列表创建下拉列表的正确方法是什么?
- cordova - 如何在 ionic 或任何混合应用程序中实现视频和音频聊天?
- fortran - 使用 OpenMP 并行化包含指针数组的可分配类型的英特尔 Fortran 代码