1. 程式人生 > 其它 >Fastadmin 自定義Tab選項卡(B表的條件查詢A表的資料,在A表裡面加B表的引數作為選項卡)

Fastadmin 自定義Tab選項卡(B表的條件查詢A表的資料,在A表裡面加B表的引數作為選項卡)

技術標籤:Fastadmin外掛php

上圖:

個人、推廣員、商業使用者都是在使用者表裡面的一個type欄位,當前訂單表通過user_id關聯了使用者表。
在這裡插入圖片描述 在這裡插入圖片描述在這裡插入圖片描述 在這裡插入圖片描述

第一步:

_initialize方法裡面加上 $this->view->assign("newList", $this->model->getNewList());

getNewList 方法如下,其實就是自定義的

public function getNewList(){
   return ['person' => __('個人'), 'genera' => __(
'推廣員'), 'business' => __('商業使用者')]; }

然後再對應的Html下面加上這個

<div class="panel-heading">
    {:build_heading(null,FALSE)}
    <ul class="nav nav-tabs" data-field="user_id">
        <li class="active"><a href="#t-all" data-value="
"
data-toggle="tab">
{:__('All')}</a></li> {foreach name="newList" item="vo"} <li><a href="#t-{$key}" data-value="{$key}" data-toggle="tab">{$vo}</a></li> {/foreach} </ul>
</div>

第二步

在對應的js裡面的index方法裡面加上這個:

// 繫結TAB事件
$('.panel-heading a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
    var field = $(this).closest("ul").data("field");
    var value = $(this).data("value");
    var options = table.bootstrapTable('getOptions');
    options.pageNumber = 1;
    options.queryParams = function (params) {
        var filter = {};
        if (value !== '') {
            filter[field] = value;
        }
        params.filter = JSON.stringify(filter);
        return params;
    };
    table.bootstrapTable('refresh', {});
    return false;
});


// 為表格繫結事件
Table.api.bindevent(table);

第三步就是接收資料處理資料了

buildparams方法主要是過濾掉了 filter欄位,改為:$filter = '{}';,不去接收get引數

$c=null;
$t=$this->request->param();
if(isset($t['filter'])){
    if($t['filter']!='{}'){
        $c=$t['filter'];
    }
}

上面這段程式碼主要是為了提前接收到傳值 filter,並且做好儲存,加上$where2查詢條件作為新條件的處理。

$where2=array();
 if($c){
     $type=(array)json_decode($c,true)['user_id'];
     $user=new \app\admin\model\User();
     $ids=$user->where(['type'=>$type[0]])->column('id');
     $where2=['user_id'=>['in',$ids]];
 }

上面這段程式碼核心思想 where in ,想必到這裡基本上就能解決問題了,程式碼再騷,問題解決才是關鍵。

下面貼出來完整的index方法跟buildparams兩個方法,講解在上面:

/**
* 檢視
*/
public function index()
{

//        $this->relationSearch=true;
   //設定過濾方法
   $this->request->filter(['strip_tags']);
   if ($this->request->isAjax()) {
       //如果傳送的來源是Selectpage,則轉發到Selectpage

       $c=null;
       $t=$this->request->param();
       if(isset($t['filter'])){
           if($t['filter']!='{}'){
               $c=$t['filter'];
           }
       }

       if ($this->request->request('keyField')) {
           return $this->selectpage();
       }

       list($where, $sort, $order, $offset, $limit) = $this->buildparams();

       $where2=array();
       if($c){
           $type=(array)json_decode($c,true)['user_id'];
           $user=new \app\admin\model\User();
           $ids=$user->where(['type'=>$type[0]])->column('id');
           $where2=['user_id'=>['in',$ids]];
       }



       $total = $this->model
           ->with(['user','maindata'])
           ->where($where)
           ->where($where2)
           ->order($sort, $order)
           ->count();

       $list = $this->model
           ->with(['user','maindata'])
           ->where($where)
           ->where($where2)
           ->order($sort, $order)
           ->limit($offset, $limit)
           ->select();

       $list = collection($list)->toArray();
       $result = array("total" => $total, "rows" => $list);

       return json($result);
   }
   return $this->view->fetch();
}


public  function buildparams($searchfields = null, $relationSearch = null)
{
    $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
    $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
    $search = $this->request->get("search", '');
    $filter = '{}';
    $op = $this->request->get("op", '', 'trim');
    $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
    $order = $this->request->get("order", "DESC");
    $offset = $this->request->get("offset/d", 0);
    $limit = $this->request->get("limit/d", 999999);
    //新增自動計算頁碼
    $page = $limit ? intval($offset / $limit) + 1 : 1;
    if ($this->request->has("page")) {
        $page = $this->request->get("page/d", 1);
    }
    $this->request->get([config('paginate.var_page') => $page]);
    $filter = (array)json_decode($filter, true);
    $op = (array)json_decode($op, true);
    $filter = $filter ? $filter : [];
    $where = [];
    $alias = [];
    $bind = [];
    $name = '';
    $aliasName = '';
    if (!empty($this->model) && $this->relationSearch) {
        $name = $this->model->getTable();
        $alias[$name] = Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
        $aliasName = $alias[$name] . '.';
    }
    $sortArr = explode(',', $sort);
    foreach ($sortArr as $index => & $item) {
        $item = stripos($item, ".") === false ? $aliasName . trim($item) : $item;
    }
    unset($item);
    $sort = implode(',', $sortArr);
    $adminIds = $this->getDataLimitAdminIds();
    if (is_array($adminIds)) {
        $where[] = [$aliasName . $this->dataLimitField, 'in', $adminIds];
    }
    if ($search) {
        $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
        foreach ($searcharr as $k => &$v) {
            $v = stripos($v, ".") === false ? $aliasName . $v : $v;
        }
        unset($v);
        $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
    }
    $index = 0;
    foreach ($filter as $k => $v) {
        if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', $k)) {
            continue;
        }
        $sym = isset($op[$k]) ? $op[$k] : '=';
        if (stripos($k, ".") === false) {
            $k = $aliasName . $k;
        }
        $v = !is_array($v) ? trim($v) : $v;
        $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
        //null和空字串特殊處理
        if (!is_array($v)) {
            if (in_array(strtoupper($v), ['NULL', 'NOT NULL'])) {
                $sym = strtoupper($v);
            }
            if (in_array($v, ['""', "''"])) {
                $v = '';
                $sym = '=';
            }
        }

        switch ($sym) {
            case '=':
            case '<>':
                $where[] = [$k, $sym, (string)$v];
                break;
            case 'LIKE':
            case 'NOT LIKE':
            case 'LIKE %...%':
            case 'NOT LIKE %...%':
                $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
                break;
            case '>':
            case '>=':
            case '<':
            case '<=':
                $where[] = [$k, $sym, intval($v)];
                break;
            case 'FINDIN':
            case 'FINDINSET':
            case 'FIND_IN_SET':
                $v = is_array($v) ? $v : explode(',', str_replace(' ', ',', $v));
                $findArr = array_values($v);
                foreach ($findArr as $idx => $item) {
                    $bindName = "item_" . $index . "_" . $idx;
                    $bind[$bindName] = $item;
                    $where[] = "FIND_IN_SET(:{$bindName}, `" . str_replace('.', '`.`', $k) . "`)";
                }
                break;
            case 'IN':
            case 'IN(...)':
            case 'NOT IN':
            case 'NOT IN(...)':
                $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
                break;
            case 'BETWEEN':
            case 'NOT BETWEEN':
                $arr = array_slice(explode(',', $v), 0, 2);
                if (stripos($v, ',') === false || !array_filter($arr)) {
                    continue 2;
                }
                //當出現一邊為空時改變操作符
                if ($arr[0] === '') {
                    $sym = $sym == 'BETWEEN' ? '<=' : '>';
                    $arr = $arr[1];
                } elseif ($arr[1] === '') {
                    $sym = $sym == 'BETWEEN' ? '>=' : '<';
                    $arr = $arr[0];
                }
                $where[] = [$k, $sym, $arr];
                break;
            case 'RANGE':
            case 'NOT RANGE':
                $v = str_replace(' - ', ',', $v);
                $arr = array_slice(explode(',', $v), 0, 2);
                if (stripos($v, ',') === false || !array_filter($arr)) {
                    continue 2;
                }
                //當出現一邊為空時改變操作符
                if ($arr[0] === '') {
                    $sym = $sym == 'RANGE' ? '<=' : '>';
                    $arr = $arr[1];
                } elseif ($arr[1] === '') {
                    $sym = $sym == 'RANGE' ? '>=' : '<';
                    $arr = $arr[0];
                }
                $tableArr = explode('.', $k);
                if (count($tableArr) > 1 && $tableArr[0] != $name && !in_array($tableArr[0], $alias) && !empty($this->model)) {
                    //修復關聯模型下時間無法搜尋的BUG
                    $relation = Loader::parseName($tableArr[0], 1, false);
                    $alias[$this->model->$relation()->getTable()] = $tableArr[0];
                }
                $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' TIME', $arr];
                break;
            case 'NULL':
            case 'IS NULL':
            case 'NOT NULL':
            case 'IS NOT NULL':
                $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                break;
            default:
                break;
        }
        $index++;
    }
    if (!empty($this->model)) {
        $this->model->alias($alias);
    }
    $model = $this->model;
    $where = function ($query) use ($where, $alias, $bind, &$model) {
        if (!empty($model)) {
            $model->alias($alias);
            $model->bind($bind);
        }
        foreach ($where as $k => $v) {
            if (is_array($v)) {
                call_user_func_array([$query, 'where'], $v);
            } else {
                $query->where($v);
            }
        }
    };
    return [$where, $sort, $order, $offset, $limit, $page, $alias, $bind];
}