Background
The company's main business is developed using the PHP language and the laravel framework. When doing some list filtering queries, the following code that is difficult to maintain often appears:
//若干代码 根据参数执行不同where if (request('has_score')) { $article = $article->with(['scores' => function ($query) { $query->where('type', self::TYPE); $query->with('user'); }]); } if (has_module('Audit')) { $article = $article->with(['auditing' => function ($query) { $query->orderBy('id', 'desc'); }]); } $article = $article->with(['videos' => function ($query) { $query->where('type', VIDEO); }])->with(['audios' => function ($query) { $ query->where('type', AUDIO); }]);
Solution
If these queries can be configured and the data is queried according to the configuration instead of judging directly through if in the code, the code will be more elegant. I develop a service package laravel-query-builder myself.
laravel-query-builder is the laravel framework to execute the query condition builder service package based on existing configuration
Install
composer require zyimm/laravelquery-builder
Require
{ "require": { "php": ">=7.0", "fideloper/proxy": "^4.0", "laravel/framework": ">=5.5" } }
Usage
/** // 目前支持条件操作符 '=', '', '>', '>=', ' 20, 'user_id'=> 'zyimm', 'user_name' => "zyimm,12" ]; //配置数据库字段查询操作 $condition =[ '=' => [ 'log_id' ], 'not_in' => [ 'user_id' ], 'between' => [ 'user_name' ], 'full_like' => [ 'user_id' ], '' => [ 'user_id' ], '>' => [ 'user_id' ] ]; DB::enableQueryLog(); //model \App\Models\Log::query() ->where(function ($query) use ($build, $data, $condition){ $build->buildQueryWhere($data ,$condition, $query); })->get(); dd(DB::getQueryLog());
Generate SQL query records as shown below:
Tips: 'in','not_in','between' ,'not_between'
These identifiers support arrays and character strings. Strings have optional ',' and '.' as delimiters.
The latest five Laravel video tutorials