mattsplat / table-queries
Laravel包,可轻松实现表格搜索、排序和关联数据
Requires
- php: ^7.2
- ext-json: *
- illuminate/console: ^5.5|^6.0
- illuminate/database: ^6.0
- nesbot/carbon: ^2.24
Requires (Dev)
- orchestra/testbench: ^4.0
- phpunit/phpunit: ^8.3
This package is auto-updated.
Last update: 2024-08-29 05:12:43 UTC
README
内容
这是什么?
设置
排序
搜索
关联
筛选
这是什么?
如果您需要以表格或类似格式查看数据,该格式结合了来自关系模型的多个数据,并且需要客户端无法提供的性能。对于大量数据,客户端渲染可能会变得太慢,因此我们可以使用服务器端渲染。如果我们依赖于来自关系表的数据,过滤、搜索或排序这些数据可能很棘手。本包旨在使这一过程更容易。
假设您有以下数据库结构
users-
id
name
company_id
companies-
id
name
sales-
id
amount
user_id
date
您可能需要显示一个包含公司名称、年度总销售额和上一年度总销售额的用户的表格。
您可以将公司名称定义为与company|name as company_name'
的简单属于关系。此格式为relation|column as alias
。此关系必须在模型上定义。这将向选择语句添加company_name,允许对其进行筛选或排序。
对于总销售额,我们可以使用sales|count(*) as sales_count
对于上一年度的总销售额,我们希望使用
'sales as year_sales' => function ($q) {
$q->selectRaw('sum(sales.amount)')->where('date', '>', today()->subYear())
}
这类似于使用
User::with(['sales' => function ($q) { $q->where('date', '>', today()->subYear()) }])
但与添加整个嵌套对象的关系不同,它添加了一个可以添加到orderBy
或where
或作为模型的属性访问的字段。
设置
使用composer安装:composer require mattsplat/table-queries
为每个查询创建一个实现TableQueryable接口的类。此类通常从控制器中调用。
$options = $request->only(['query', 'limit', 'page', 'orderBy', 'ascending', 'filter']); $results = (new NoteTableQuery($options))->get(); return $results;
排序
TableQueryBuilder类接受orderBy
和ascending
选项,可以在setOptions方法中传递。
$results = (new TableQueryBuilder($query))
->setOptions(['orderBy' => 'name', 'ascending' => true]);
或者可以直接调用order方法并传递s参数
$results = (new TableQueryBuilder($query))->order($orderBy, $ascending)
在这种情况下,如果没有提供ascending
,则默认顺序为desc
搜索
您可以使用搜索选项搜索多个字段,甚至是关联字段中的文本。
$results = (new TableQueryBuilder($query))
->setOptions(['search' => 'something']);
或直接调用
$results = (new TableQueryBuilder($query))->search($searchText)
关联
可以使用常规的with方法加载关联,但如果您需要按此数据排序或筛选,则不会起作用。使用易于阅读的语法,您可以向查询本身添加基本的关联数据。
public function relationalColumns()
{
return [
/// relation name | column name as alias
/// if alias is not supplied it will be relation_column
'company|name as company',
/// if name is multiple words it will be interpreted as raw sql
/// in this case an alias is required
'company|concat(users.name, "-", users.id) as company_concat',
/// optionally a callback can be used to modify the query
/// the column will not be needed here as a select can be added to the query
'notes as notes_count' => function ($q) {
return $q->selectRaw('count(*)');
},
];
}
筛选
可以使用类似于SQL的语法对特定列调用筛选。筛选数组可以以格式filter=column:operator:value
在options数组中传递
$filters = [
'age:>:21',
'start_date:gte:11/21/2009',
'id:in:33,44,200'
]
$results = (new TableQueryBuilder($query))
->setOptions(['filters' => $filters]);
支持的运算符包括
'gt' , '>', 'gte' , '>=', 'eq' , '=', 'lte' , '<=', 'lt' , '<',
'ne' , '!=', 'like', 'in', 'nin' , 'not in', 'between', 'rlike'
由于这不直接从请求中读取,如果您的请求格式不同,可以在将其发送到类之前对其进行修改。
示例GET请求/users?filter[id]=nin:9&filter[name]=like:S%
$filters = collect($request->filter)->map(function ($name, $f) {
return $name.$f;
})