zazmaster/query-builder-parser-eloquent

使用 jQuery-QueryBuilder 时,自动构建复杂的 Eloquent & QueryBuilder 查询

0.2 2020-03-03 05:20 UTC

This package is auto-updated.

Last update: 2024-09-29 05:49:27 UTC


README

Eloquent 版本的 https://github.com/timgws/QueryBuilderParser,有关问题 timgws/QueryBuilderParser#18

QueryBuilderParser 主要设计用于 Laravel 项目内部,但也可以通过使用 Illuminate/Database 在 Laravel 之外的项目中使用。

一个简单易用的 jQuery QueryBuilder 插件的查询构建器。

使用 QueryBuilderParser

从 QueryBuilder 规则构建新的查询。

    use timgws\QueryBuilderParser;

    $table = DB::table('table_of_data_to_integrate');
    $qbp = new QueryBuilderParser(
        // provide here a list of allowable rows from the query builder.
        // NOTE: if a row is listed here, you will be able to create limits on that row from QBP.
        array( 'name', 'email' )
    );

    $query = $qbp->parse($input['querybuilder'], $table);

    $rows = $query->get();
    return Response::JSON($rows);

jQuery QueryBuilder

这个查询提交后将创建以下 SQL 查询

SELECT * FROM table_of_data_to_integrate WHERE `name` LIKE '%tim%' AND `email` LIKE '%@gmail.com'

从 MongoDB 获取结果

    use timgws\QueryBuilderParser;

    $table = DB::collection('data');
    $qbp = new QueryBuilderParser(
        // provide here a list of allowable rows from the query builder.
        // NOTE: if a row is listed here, you will be able to create limits on that row from QBP.
        array( 'name', 'email' )
    );

    $query = $qbp->parse($input['querybuilder'], $table);

    $rows = $query->get();
    return Response::JSON($rows);

这个查询提交后将创建以下 MongoDB 查询

    {
      "$and": [
        {
          "name": {
            "$regex": "tim"
          }
        },
        {
          "email": {
            "$regex": "@gmail\\.com$"
          }
        }
      ]
    }

注意,要使用此功能,您需要安装和配置 jenssegers/mongodb

集成示例

与 jQuery Datatables 集成

与 Datatables 混合,jQuery QueryBuilder 提供了无限的数据过滤选项,并可以实时查看结果。

    use timgws\QueryBuilderParser;
    
    class AdminUserController {
        function displayUserDatatable() {
            /* builder is POST'd by the datatable */
            $queryBuilderJSON = Input::get('rules');
            
            $show_columns = array('id', 'username', 'email_address');
            
            $query = new QueryBuilderParser($show_columns);
            
            /** Illuminate/Database/Query/Builder $queryBuilder **/
            $queryBuilder = $query->parse(DB::table('users'));
            
            return Datatable::query($queryBuilder)
                ->showColumns($show_columns)
                ->orderColumns($show_columns)
                ->searchColumns($show_columns)
                ->make()
        }
    }

在客户端,需要一点魔法来使一切正常工作。

    // the default rules, what will be used on page loads...
    var datatablesRequest = {};
    var _rules = defaultRules = {"condition":"AND","rules":[
        {"id":"active","field":"active","type":"integer","input":"radio","operator":"equal","value":"1"}
    ]};

    // a button/link that is used to update the rules.
    function updateFilters() {
        _rules = $('#querybuilder').queryBuilder('getRules');
        reloadDatatables();
    }

    function filterChange() {
        var _json = JSON.stringify( _rules );
        datatablesRequest = { rules: _json };
    }

    filterChange();

    function reloadDatatables() {
        /* Datatables first... */
        filterChange();

        $('.dataTable').each(function() {
            dt = $(this).dataTable();
            dt.fnDraw();
        })
    }

    jQuery(document).ready(function(){
        // dynamic table
        oTable = jQuery('.datatable').dataTable({
            "fnServerParams": function(aoData) {
                // add the extra parameters from the jQuery QueryBuilder to the Datatable endpoint...
                $.each(datatablesRequest , function(k,v){
                    aoData.push({"name": k, "value": v});
                })
            }
        })
    });

使用 JoinSupportingQueryBuilderParser

JoinSupportingQueryBuilderParserQueryBuilderParser 的一个版本,支持构建更复杂的查询。

    $joinFields = array(
        'join1' => array(
            'from_table'      => 'master',
            'from_col'        => 'm_col',
            'to_table'        => 'subtable',
            'to_col'          => 's_col',
            'to_value_column' => 's_value',
        ),
        'join2' => array(
            'from_table'      => 'master2',
            'from_col'        => 'm2_col',
            'to_table'        => 'subtable2',
            'to_col'          => 's2_col',
            'to_value_column' => 's2_value',
            'not_exists'      => true,
        )
    );

    $table = DB::table('table_of_data_to_integrate');
    $jsqbp = new JoinSupportingQueryBuilderParser($fields, $this->getJoinFields());
    $test = $parser->parse($json, $builder);

这将构建一个类似于以下 SQL 查询

select * where exists (select 1 from `subtable` where subtable.s_col = master.m_col and `s_value` < ?)

对于简单查询,QueryBuilderParser 应该足够。

导出 CSV 文件

顺便提一下,导出 CSV 文件有正确和错误的方法。

对于正确的方法,请查看 StackOverflow 上的问题,如何在 PHP 中输出 Excel 能正确读取的 UTF-8 CSV?

报告问题

我在多个项目中使用此代码,所以如果您确实发现一个问题,请随时通过 GitHub 的错误跟踪器 报告此项目的问题。

或者,将项目分支出来并提交一个 pull request :)