PHP 实现 form 统一提交的方法

    先讲一下写本文要解决的问题,后端有很多from表单查询列表,之前的写法自己写原生sql或者orm支持的封装的多where查询,在自己的项目的model或者repository一般都封装了许多要查询的字段校验查询条件,这样一来又要复写许多代码,很多框架都会封装许多interface,但是实际项目中每个model维护的字段都不一样。
    下面讲一下实现思路:
     1. 封装一个创建查询表的接口buildFrom 来接接收参数创建表单。
     2.封装一个接收前端提交过来的查询参数拼装需要搜索的查询sql(可session或cache中)。
     3.自己模型需要serach的时候传一个bysearch参数来接收存的sql。

    buildFrom代码控制器代码逻辑如下:
    ```
    <?php   
  public function buildForm($module = '', $searchFields = '', $fieldParams = '', $actionURL = '', $queryID = 0)
{
    if($queryID == 0 and $this->session->queryID != false)
    {
        $queryID = $this->session->queryID;
        $this->session->set('queryID', false);
    }

    if(empty($module)){
        $module       = empty($module) ?       $this->session->searchParams['module'] : $module;
        $searchFields = empty($searchFields) ? json_decode($this->session->searchParams['searchFields'], true) : $searchFields;
        $fieldParams  = empty($fieldParams) ?  json_decode($this->session->searchParams['fieldParams'], true)  : $fieldParams;
    }else{
        $sessionKey = 'searchParams'.$module;
        $searchFields = empty($searchFields) ? json_decode($this->session->$sessionKey['searchFields'], true) : $searchFields;
        $fieldParams  = empty($fieldParams) ?  json_decode($this->session->$sessionKey['fieldParams'], true)  : $fieldParams;
  }

  $this->search->initSession($module, $searchFields, $fieldParams);

    $this->json(array(
        'module' => $module,
        "fields" => $searchFields,
        "params" => $this->search->setDefaultParams($searchFields, $fieldParams),
    ));
}
// 返回查询sql
public function buildQuery($queryID = '')
 {
  $this->search->buildQuery();\
  $this->json(array("code"=>200));
  }

```
model代码用的initSession这个方法:
```
<?php
class searchModel extends model
{

/**
 * Set search params to session.
 *
 * @param  array    $searchConfig
 * @access public
 * @return void
 */
public function setSearchParams($searchConfig)
{
    $searchParams['module']       = $searchConfig['module'];
    $searchParams['searchFields'] = json_encode($searchConfig['fields']);
    $searchParams['fieldParams']  = json_encode($searchConfig['params']);
    $searchParams['actionURL']    = $searchConfig['actionURL'];
    $searchParams['queryID']      = isset($searchConfig['queryID']) ? $searchConfig['queryID'] : 0;

    /* remove onlybody for url*/
    $onlybodyParam = $this->config->requestType == 'GET' ? '&onlybody=yes' : '?onlybody=yes';
    $searchParams['actionURL'] = str_replace($onlybodyParam, '', $searchParams['actionURL']);

    //防止多个浏览器页面同时访问,session乱的问题
    $this->session->set('searchParams'.$searchConfig['module'], $searchParams);
    $this->session->set('searchParams', $searchParams);
}

/**
 * Build the query to execute.
 *
 * @access public
 * @return void
 */
public function buildQuery()
{
    /* Init vars. */
    $where      = '';
    $groupItems = $this->config->search->groupItems;
    $groupAndOr = strtoupper($this->post->groupAndOr);
    if($groupAndOr != 'AND' and $groupAndOr != 'OR') $groupAndOr = 'AND';

    for($i = 1; $i <= $groupItems * 2; $i ++)
    {
        /* The and or between two groups. */
        if($i == 1) $where .= '(( 1  ';
        if($i == $groupItems + 1) $where .= " ) $groupAndOr ( 1 ";

        /* Set var names. */
        $fieldName    = "field$i";
        $andOrName    = "andOr$i";
        $operatorName = "operator$i";
        $valueName    = "value$i";

        if($this->post->$fieldName == '' || $this->post->$valueName == ''){
            continue;
        }

        /* Skip empty values. */
        if($this->post->$valueName == false) continue;
        if($this->post->$valueName == 'null') $this->post->$valueName = '';  // Null is special, stands to empty.
        if($this->post->$valueName == 'ZERO') $this->post->$valueName = 0;   // ZERO is special, stands to 0.

        if($this->post->module == 'suppliergoods'){
            if($this->post->$fieldName == 'createdDate'){
                $this->post->$fieldName = 'left(`createdDate`,10)';
                $this->post->$valueName = substr($this->post->$valueName, 0, 10);

            }
        }else if($this->post->module == 'surveyexam'){
            if($this->post->$fieldName == 'a.status'){
                $this->post->$fieldName = 'a.`status`';
            }
        }else if($this->post->module == 'agent'){
            if($this->post->$fieldName == 'createdBy'){
                $this->post->$fieldName = 'U.`realname`';
            }
        } else if($this->post->module == 'itembank'){
            if($this->post->$fieldName == 'createdBy'){
                $this->post->$fieldName = 't2.`realname`';
            }
        }else if($this->post->module == 'performanceexam'){
            if($this->post->$fieldName == 'checkedBy'){
                $this->post->$fieldName = 'b.`realname`';
            }
        }else if($this->post->module == 'knowledge'){
            if($this->post->$fieldName == 'a.publishDate'){
                $this->post->$fieldName = 'left(a.`publishDate`,10)';
                $this->post->$valueName = substr($this->post->$valueName, 0, 10);
            }
        }else if($this->post->module == 'complain'){
            if($this->post->$fieldName == 't1.processDate'){
                $this->post->$fieldName = 'left(t1.`processDate`,10)';
                $this->post->$valueName = substr($this->post->$valueName, 0, 10);
            }

            if($this->post->$fieldName == 't1.appiontDate'){
                $this->post->$fieldName = 'left(t1.`appiontDate`,10)';
                $this->post->$valueName = substr($this->post->$valueName, 0, 10);
            }
        }else if($this->post->module == 'turnover'){
          if($this->post->$fieldName = 'date'){
                $this->post->$fieldName = 'left(`date`, 10)';
            }

            if($this->post->$fieldName == 'left(`date`, 10)'){
                $this->post->$fieldName = 'left(`date`, 10)';
                $this->post->$valueName = substr($this->post->$valueName, 0, 10);
            }elseif($this->post->$fieldName == 'left(`date`, 7)'){
                $this->post->$fieldName = 'left(`date`, 7)';
                $this->post->$valueName = substr($this->post->$valueName, 0, 7);
            }elseif($this->post->$fieldName == 'count(`order`)'){
                $this->post->$fieldName = 'count(`order`)';
            }elseif($this->post->$fieldName == 'sum(`amount`)'){
                $this->post->$fieldName = 'sum(`amount`)';
            }
        }
        if(in_array($this->post->$fieldName, array('A.editedDate','attendDate','signinDate','createdDate','editedDate','startDate','endDate','assignDate','transformationDate','nextDate','a.createdDate','appointDate','releaseDate','a.uploadDate','A.assignDate','A.appointDate','A.createdDate','a.auditDate','A.transformationDate'))) {
            $this->post->$fieldName = 'left('.$this->post->$fieldName.',10)';
            $this->post->$valueName = substr($this->post->$valueName, 0, 10);
        }

        /* Set and or. */
        $andOr = strtoupper($this->post->$andOrName);
        if($andOr != 'AND' and $andOr != 'OR') $andOr = 'AND';
        $where .= " $andOr ";

        /* Set filed name. not use `` if has alias. */
        if(strpos($this->post->$fieldName, '.') === false)
        {

            if(strpos(',suppliergoods|surveyexam', $this->post->module)){
                $where .= $this->post->$fieldName;
                if($this->post->module == 'surveyexam' && $this->post->$fieldName == 'a.`status`'){
                    if($this->post->$valueName == 1){

                    }elseif($this->post->$valueName == 2){

                    }
                }
            }elseif($this->post->module == 'turnover'){
                if($this->post->$fieldName == 'left(`date`, 10)'){
                    $where .= $this->post->$fieldName;
                }elseif($this->post->$fieldName == 'left(`date`, 7)'){
                    $where .= $this->post->$fieldName;
                }elseif($this->post->$fieldName == 'count(`order`)'){
                    $where .= $this->post->$fieldName;
                }elseif($this->post->$fieldName == 'sum(`amount`)'){
                    $where .= $this->post->$fieldName;
                }else{
                    $where .= '`' . $this->post->$fieldName . '` ';
                }
            }else{
                if(in_array($this->post->$fieldName, array('left(A.editedDate,10)','left(A.transformationDate,10)','left(attendDate,10)','left(signinDate,10)','left(createdDate,10)','left(editedDate,10)','left(startDate,10)','left(endDate,10)'
          ,'left(assignDate,10)','left(transformationDate,10)','left(nextDate,10)','left(a.createdDate,10)','left(appointDate,10)','left(releaseDate,10)','left(a.uploadDate,10)','left(A.assignDate,10)','left(A.appointDate,10)','left(a.auditDate,10)'))){
                    $where.= $this->post->$fieldName;
                }else{
                    $where .= '`' . $this->post->$fieldName . '` ';
                }

            }

        }
        elseif($this->post->$fieldName == 'contract.productLine')
        {
            /* Search contracts by product or product line. */
            $where .= ' id ';
        }
        else
        {
            $where .= $this->post->$fieldName . ' ';
        }

        /* Set operator. */
        $value    = $this->post->$valueName;
        $operator = $this->post->$operatorName;
        if(!isset($this->lang->search->operators[$operator])) $operator = '='

        if($operator == "include")
        {
            if($this->post->$fieldName == 'contract.productLine')
            {
                $where .= helper::dbIN($contracts);
            }
            else
            {
                if($this->post->$fieldName == 'o.product') $value = ',' . $value . ',';
                $where .= ' LIKE ' . $this->dbh->quote("%" . trim($value) ."%");
            }
        }
        elseif($operator == "notinclude")
        {
            if($this->post->$fieldName == 'contract.productLine')
            {
                $where .= ' NOT ' . helper::dbIN($contracts);
            }
            else
            {
                $where .= ' NOT LIKE ' . $this->dbh->quote("%" . trim($value) . "%");
            }
        }
        elseif($operator == 'belong')
        {
            if($this->post->$fieldName == 'module' or $this->post->$fieldName == 'area' or $this->post->$fieldName == 'industry')
            {
                if($value == 0) $where .= ' RLIKE ' . $this->dbh->quote("[0-9]*");
                $allModules = $this->loadModel('tree')->getAllChildId($value);
                if($allModules) $where .= helper::dbIN($allModules);
            }
            elseif($this->post->$fieldName == 'dept')
            {
                $allDepts = $this->loadModel('dept')->getAllChildId($value);
                $where .= helper::dbIN($allDepts);
            }
            elseif($this->post->$fieldName == 'contract.productLine')
            {
                $where .= " = '-1'";
            }
            else
            {
                $where .= ' = ' . $this->dbh->quote(trim($value)) . ' ';
            }
        }
        else
        {
            if($this->post->$fieldName == 'contract.productLine')
            {
                if($operator == '=')
                {
                    $where .= helper::dbIN($contracts);
                }
                elseif($operator == '!=')
                {
                    $where .= ' NOT ' . helper::dbIN($contracts);
                }
                else
                {
                    $where .= " = '-1'";
                }
            }
            else
            {
                $where .= $operator . ' ' . $this->dbh->quote(trim($value)) . ' ';
            }
        }
    }
    $where .=" ))";
    //echo $where;exit;
    /* Save to session. */
    $querySessionName = $this->post->module . 'Query';
    $formSessionName  = $this->post->module . 'Form';
    $this->session->set($querySessionName, $where);
    $this->session->set($formSessionName,  $_POST);
}

/**
 * Init the search session for the first time search.
 *
 * @param  string   $module
 * @param  array    $fields
 * @param  array    $fieldParams
 * @access public
 * @return void
 */
public function initSession($module, $fields, $fieldParams)
{
    $formSessionName  = $module . 'Form';
    if($this->session->$formSessionName != false) return;

    for($i = 1; $i <= $this->config->search->groupItems * 2; $i ++)
    {
        /* Var names. */
        $fieldName    = "field$i";
        $andOrName    = "andOr$i";
        $operatorName = "operator$i";
        $valueName    = "value$i";

        $currentField = key($fields);
        $operator     = isset($fieldParams[$currentField]['operator']) ? $fieldParams[$currentField]['operator'] : '=';

        $queryForm[$fieldName]    = key($fields);
        $queryForm[$andOrName]    = 'and';
        $queryForm[$operatorName] = $operator;
        $queryForm[$valueName]    =  '';

        if(!next($fields)) reset($fields);
    }
    $queryForm['groupAndOr'] = 'and';
    $this->session->set($formSessionName, $queryForm);
}

/**
 * Set default params for selection.
 *
 * @param  array  $fields
 * @param  array  $params
 * @access public
 * @return array
 */
public function setDefaultParams($fields, $params)
{
    $hasProduct = false;
    $hasProject = false;
    $hasUser    = false;
    $hasOrganize    = false;
    $hasOfflinecourse = false;
    $hasAgentleavel = false;
    $groupUsers = false;

    $fields     = array_keys($fields);
    foreach($fields as $fieldName)
    {
        if(empty($params[$fieldName])) continue;
        if($params[$fieldName]['values'] == 'products') $hasProduct = true;
        if($params[$fieldName]['values'] == 'users')    $hasUser    = true;
        if($params[$fieldName]['values'] == 'projects') $hasProject = true;
        if($params[$fieldName]['values'] == 'organize') $hasOrganize = true;
        if($params[$fieldName]['values'] == 'offlinecourses') $hasOfflinecourse = true;
        if($params[$fieldName]['values'] == 'agentlevels') $hasAgentleavel = true;
        if($params[$fieldName]['values'] == 'process') $hasProcess = true;
        if($params[$fieldName]['values'] == 'welfare') $hasWelfarerecord = true;
        if($params[$fieldName]['values'] == 'groupUsers') $groupUsers = true;//获取自己的下级账户
        if($params[$fieldName]['values'] == 'onlinecourseagentlevels') $hasonlinecourseagentlevel= true;//获取自己的下级账户
        if($params[$fieldName]['values'] == 'selectlevel') $selectlevel= true;//获取自己的下级账户

        if($params[$fieldName]['values'] == 'smallwx') $smallwx = true;//获取微信小号
        if($params[$fieldName]['values'] == 'linkwx') $linkwx = true;//获取微联锁号

        if($params[$fieldName]['values'] == 'contract') $contract = true;
        if($params[$fieldName]['values'] == 'gthcontract') $gthcontract = true;
        if($params[$fieldName]['values'] == 'thirdorganize') $thirdorganize = true;
        if($params[$fieldName]['values'] == 'salerole') $hasSalerole = true;
        if($params[$fieldName]['values'] == 'offlineteacher') $hasOfflineteacher = true;
        if($params[$fieldName]['values'] == 'complainlevel') $hascomplainlevel = true;
    }
    if($hascomplainlevel){
        $complainlevels= $this->loadModel('complainlevel')->getComplainLevelPairs();
    }

    if($hasOfflineteacher){
        $offlineteachers = $this->loadModel('offlineteacher')->getofflineteacherPairs();
    }

    if($hasSalerole){
        $Saleroles = $this->loadModel('agent')->getSaleRoleLists();
    }

    if($thirdorganize)
    {
        $thirdorganizes = $this->loadModel('organize')->getThirdsOrganizePairs();
    }
    if($gthcontract)
    {
        $gthcontracts = $this->loadModel('gthcontract','gth')->getContractList();
    }
    if($contract)
    {
        $contracts = $this->loadModel('contract','fi')->getContractList();
    }

    if($smallwx)
    {
        $smallwxs = $this->loadModel('agent')->getSmallwxPairs();
    }
    if($linkwx)
    {
        $linkwxs = $this->loadModel('agent')->getLinkwxPairs();
    }

    if($selectlevel)
    {
        $selectlevels = $this->loadModel('onlinestudy')->getdoubleonlinelist();
    }

    if($hasonlinecourseagentlevel)
    {
        $hasonlinecourseagentlevels = $this->loadModel('onlinecourseagentlevel')->getOnlineCourseAgentlevelList();
    }
    if($hasWelfarerecord)
    {
        $hasWelfarerecords = $this->loadModel('welfare')->getWelfarePairs();
    }

    if($hasAgentleavel)
    {
        $hasAgentleavels = $this->loadModel('agentlevel')->getAgentLevelList();
    }

    if($hasOfflinecourse)
    {
        $offlinecourses = $this->loadModel('offlinecourse')->getOfflinecoursePairs();
    }
    if($hasUser)
    {
        $users         = $this->loadModel('user')->getPairs('nodeleted,noforbidden');
        $users['$@me'] = $this->lang->search->me;
    }
    if($hasOrganize)
    {
        $organizes         = $this->loadModel('organize')->getPairs('nodeleted,noforbidden');
    }
    if($hasProcess){
        $process         = $this->loadModel('process')->getProcessInfo();
    }
    if($groupUsers){//getUserAllPairs
        $groupList = $this->loadModel('group')->getgroupByParentId($this->app->user->groupId);//$userGroup->group
        if(!empty($groupList)){
            $groupList = array_keys($groupList);
            $userPairs = $this->loadModel('group')->getUserAllPairs($groupList);
        }else{
            $userPairs = [];
        }
        $userPairs['$@me'] = $this->lang->search->me;
    }
    if($hasProduct) $products = $this->loadModel('product', 'sys')->getPairs();
    if($hasProject) $projects = $this->loadModel('project', 'proj')->getPairs();

    foreach($fields as $fieldName)
    {
        if(!isset($params[$fieldName])) $params[$fieldName] = array('operator' => '=', 'control' => 'input', 'values' => '');
        if($params[$fieldName]['values'] == 'users')    $params[$fieldName]['values']  = $users;
        if($params[$fieldName]['values'] == 'products') $params[$fieldName]['values']  = $products;
        if($params[$fieldName]['values'] == 'projects') $params[$fieldName]['values']  = $projects;
        if($params[$fieldName]['values'] == 'organize') $params[$fieldName]['values']  = $organizes;
        if($params[$fieldName]['values'] == 'offlinecourses') $params[$fieldName]['values'] = $offlinecourses;
        if($params[$fieldName]['values'] == 'agentlevels') $params[$fieldName]['values'] = $hasAgentleavels;
        if($params[$fieldName]['values'] == 'process') $params[$fieldName]['values'] = $process;
        if($params[$fieldName]['values'] == 'welfare') $params[$fieldName]['values'] = $hasWelfarerecords;
        if($params[$fieldName]['values'] == 'groupUsers') $params[$fieldName]['values'] = $userPairs;
        if($params[$fieldName]['values'] == 'onlinecourseagentlevels') $params[$fieldName]['values'] = $hasonlinecourseagentlevels;
        if($params[$fieldName]['values'] == 'selectlevel') $params[$fieldName]['values'] = $selectlevels;

        if($params[$fieldName]['values'] == 'smallwx') $params[$fieldName]['values'] = $smallwxs;
        if($params[$fieldName]['values'] == 'linkwx') $params[$fieldName]['values'] = $linkwxs;
        if($params[$fieldName]['values'] == 'contract') $params[$fieldName]['values'] = $contracts;
        if($params[$fieldName]['values'] == 'gthcontract') $params[$fieldName]['values'] = $gthcontracts;
        if($params[$fieldName]['values'] == 'thirdorganize') $params[$fieldName]['values'] = $thirdorganizes;
        if($params[$fieldName]['values'] == 'salerole') $params[$fieldName]['values'] = $Saleroles;
        if($params[$fieldName]['values'] == 'offlineteacher') $params[$fieldName]['values'] = $offlineteachers;
        if($params[$fieldName]['values'] == 'complainlevel') $params[$fieldName]['values'] = $complainlevels;

        if(is_array($params[$fieldName]['values']))
        {
            /* For build right sql when key is 0 and is not null.  e.g. confirmed field. */
            if(isset($params[$fieldName]['values'][0]) and $params[$fieldName]['values'][0] !== '')
            {
                $params[$fieldName]['values'] = array('ZERO' => $params[$fieldName]['values'][0]) + $params[$fieldName]['values'];
                unset($params[$fieldName]['values'][0]);
            }
            else
            {
                $params[$fieldName]['values']  = $params[$fieldName]['values'];// + array('null' => $this->lang->search->null);
            }
        }
    }
    return $params;
}

/**
 * Get a query.
 *
 * @param  int    $queryID
 * @access public
 * @return string
 */
public function getQuery($queryID)
{
    $query = $this->dao->findByID($queryID)->from(TABLE_USERQUERY)->fetch();
    if(!$query) return false;

    /* Decode html encode. */
    $query->form = htmlspecialchars_decode($query->form, ENT_QUOTES);
    $query->sql  = htmlspecialchars_decode($query->sql, ENT_QUOTES);

    $query->form = unserialize($query->form);
    $query->sql  = $this->replaceDynamic($query->sql);
    return $query;
}

/**
 * Save current query to db.
 *
 * @access public
 * @return void
 */
public function saveQuery()
{
    $sqlVar  = $this->post->module  . 'Query';
    $formVar = $this->post->module  . 'Form';
    $sql     = $this->session->$sqlVar;
    if(!$sql) $sql = ' 1 = 1 ';

    $query = fixer::input('post')
        ->add('account', $this->app->user->account)
        ->add('form', serialize($this->session->$formVar))
        ->add('sql',  $sql)
        ->get();
    $this->dao->insert(TABLE_USERQUERY)->data($query)->autoCheck()->check('title', 'notempty')->exec();
}

/**
 * Get title => id pairs of a user.
 *
 * @param  string    $module
 * @access public
 * @return array
 */
public function getQueryPairs($module)
{
    $queries = $this->dao->select('id, title')
        ->from(TABLE_USERQUERY)
        ->where('account')->eq($this->app->user->account)
        ->andWhere('module')->eq($module)
        ->orderBy('id_asc')
        ->fetchPairs();
    if(!$queries) return array('' => $this->lang->search->myQuery);
    $queries = array('' => $this->lang->search->myQuery) + $queries;
    return $queries;
}

/**
 * Get records by the conditon.
 *
 * @param  string    $module
 * @param  string    $moduleIds
 * @param  string    $conditions
 * @access public
 * @return array
 */
public function getBySelect($module, $moduleIds, $conditions)
{
    if($module == 'story')
    {
        $pairs = 'id,title';
        $table = 'zt_story';
    }
    else if($module == 'task')
    {
        $pairs = 'id,name';
        $table = 'zt_task';
    }
    $query    = '`' . $conditions['field1'] . '`';
    $operator = $conditions['operator1'];
    $value    = $conditions['value1'];

    if(!isset($this->lang->search->operators[$operator])) $operator = '=';
    if($operator == "include")
    {
        $query .= ' LIKE ' . $this->dbh->quote("%$value%");
    }
    elseif($operator == "notinclude")
    {
        $where .= ' NOT LIKE ' . $this->dbh->quote("%$value%");
    }
    else
    {
        $query .= $operator . ' ' . $this->dbh->quote($value) . ' ';
    }

    foreach($moduleIds as $id)
    {
        if(!$id) continue;
        $title = $this->dao->select($pairs)
            ->from($table)
            ->where('id')->eq((int)$id)
            ->andWhere($query)
            ->fetch();
        if($title) $results[$id] = $title;
    }
    if(!isset($results)) return array();
    return $this->formatResults($results, $module);
}

/**
 * Format the results.
 *
 * @param  array    $results
 * @param  string   $module
 * @access public
 * @return array
 */
public function formatResults($results, $module)
{
    /* Get title field. */
    $title = ($module == 'story') ? 'title' : 'name';
    $resultPairs = array('' => '');
    foreach($results as $result) $resultPairs[$result->id] = $result->id . ':' . $result->$title;
    return $resultPairs;
}

/**
  Replace dynamic account and date.
 *
 * @param  string $query
 * @access public
 * @return string
 */
public function replaceDynamic($query)
{
    $this->app->loadClass('date');
    $lastWeek  = date::getLastWeek();
    $thisWeek  = date::getThisWeek();
    $lastMonth = date::getLastMonth();
    $thisMonth = date::getThisMonth();
    $yesterday = date::yesterday();
    $today     = date::today();
    if(strpos($query, '$') !== false)
    {
        $query = str_replace('$@me', $this->app->user->account, $query);
        $query = str_replace("'\$lastMonth'", "'" . $lastMonth['begin'] . "' and '" . $lastMonth['end'] . "'", $query);
        $query = str_replace("'\$thisMonth'", "'" . $thisMonth['begin'] . "' and '" . $thisMonth['end'] . "'", $query);
        $query = str_replace("'\$lastWeek'",  "'" . $lastWeek['begin']  . "' and '" . $lastWeek['end']  . "'", $query);
        $query = str_replace("'\$thisWeek'",  "'" . $thisWeek['begin']  . "' and '" . $thisWeek['end']  . "'", $query);
        $query = str_replace("'\$yesterday'", "'" . $yesterday          . "' and '" . $yesterday        . "'", $query);
        $query = str_replace("'\$today'",     "'" . $today              . "' and '" . $today            . "'", $query);
    }
    return $query;
}

/**
 * replace defined table names.
 *
 * @param  string $sql
 * @access public
 * @return void
 */
public function replaceTableNames($sql)
{
    if(preg_match_all("/TABLE_[A-Z]+/", $sql, $out))
    {
        foreach($out[0] as $table)
        {
            if(!defined($table)) continue;
            $sql = str_replace($table, trim(constant($table), '`'), $sql);
        }
    }
    return $sql;
}
}

// 调用查询逻辑 配置语言包 lang.php
if(!isset($lang->agentlevel)) $lang->agentlevel = new stdclass();
$lang->agentlevel->id = 'ID';
$lang->agentlevel->type = '类型';
$lang->agentlevel->levleId = '等级名称';
$lang->agentlevel->sort = '排序';
$lang->agentlevel->discount = '折扣';
//配置查询参数 config.php
global $lang, $app;
$app->loadLang('agentlevel','crm');
$config->agentlevel->search['module'] = 'agentlevel';
$config->agentlevel->search['fields']['type']                  = $lang->agentlevel->type;
$config->agentlevel->search['fields']['levleId']               = $lang->agentlevel->levleId;
$config->agentlevel->search['fields']['discount']              = $lang->agentlevel->discount;
$config->agentlevel->search['fields']['goodsPrice']            = $lang->agentlevel->goodsPrice;
$config->agentlevel->search['params']['type']      = array('operator' => '=', 'control' => 'select', 'values' => $lang->agentlevel->typeList,'class'=>'');
$config->agentlevel->search['params']['levleId']     = array('operator'=> '=', 'control' => 'select','values' => 'agentlevels','class'=>'');
$config->agentlevel->search['params']['discount']  = array('operator' => 'include', 'control' => 'input', 'values' => '');
// 控制器里调用controller.php
public function browse($mode = 'all',$search = '', $orderBy = 'id_desc', $recTotal = 0, $recPerPage = 20, $pageID = 1)
{     
  $this->app->loadClass('pager', $static = true);
  $pager = new pager($recTotal, $recPerPage, $pageID);             
  $customers = $this->agentlevel->getList($mode = $mode, $orderBy, $pager,$search);

  $data['title'] = $this->lang->service->list;
  $data['mode'] = $mode;
  $data['orderBy'] = $orderBy;
  $data['pager'] = $this->loadModel('common', 'sys')->getPager($pager);//以数组形式返回
  $data['agentlevel'] = (array)$customers;//查询数据

  $this->loadModel('search', 'sys');
  $this->search->setSearchParams($this->config->agentlevel->search);
  $this->json($data);
}
// model.php
public function getList($mode = 'all', $orderBy = 'id_desc', $pager = null,$search = '')
{
  if(strpos($orderBy, 'id') === false){
  if(empty($orderBy)){
  $orderBy .= 'id_desc';
  }else{
  $orderBy .= ', id_desc';
   }
 } 
 if($this->session->agentlevelQuery === false) $this->session->set('agentlevelQuery', ' 1 = 1');
 $contractQuery = $this->loadModel('search', 'sys')->replaceDynamic($this->session->agentlevelQuery);
 return $this->dao->select('*')->from(TABLE_AGENTLEVEL)
 ->where('1')->eq(1)
 ->andWhere('status')->ne('99')
 ->beginIF(strtolower($search) == 'bysearch')->andWhere($contractQuery)->fi()
 ->orderBy($orderBy)
 ->page($pager)
 ->fetchAll();
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 3

这么多if,我似乎嗅到了cms的味道

4年前 评论
lar_cainiao (楼主) 4年前

我头炸了,你赔!

4年前 评论

写的太复杂了,个人是在 repository 里面使用 默认查询字段,再配合 except、only、merge 查询字段。如果项目比较复杂,查询条件个人参考的是 es。

4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!