首页 > 解决方案 > 如果字段为空,则在限制参数中设置 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);

    }

标签: php

解决方案


轻而易举:

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)来完全禁用限制。


推荐阅读