laravelha/support

1.0.4 2020-10-07 22:48 UTC

This package is auto-updated.

Last update: 2024-09-19 07:29:34 UTC


README

Laravel 开发支持包

安装

composer require laravelha/support

功能

  1. 模型特性
    • 可表化
    • 请求查询可构建

Tableable 如何工作

Tableable 配置数据表中表示的模型。

要求

步骤

  1. 在模型上导入特性。
use Laravelha\Support\Traits\Tableable;

class Modelo extends Model {
    //
}
  1. 在类中添加特性。
class Modelo extends Model {
    use Tableable;
    //
}
  1. 实现 getColumns 方法。
    /**
     * ['data' => 'columnName', 'searchable' => true, 'orderable' => true, 'linkable' => false]
     *
     * searchable and orderable is true by default
     * linkable is false by default
     *
     * @return array[]
     */
    public static function getColumns(): array
    {
        return [
            ['data' => 'id', 'linkable' => true],
            ['data' => 'title'],
            ['data' => 'subtitle'],
            ['data' => 'slug'],
            ['data' => 'content'],
        ];
    }

默认情况下,'searchable' 和 'orderable' 选项为 'true',但如果没有告知,'linkable' 为 'false'。

  1. 在索引动作中获取列配置。
public function index()
{
    $columns = Model::getColumns();

    return view('models.index', compact('columns'));
}
  1. 在控制器中创建数据动作。
public function data()
{
    return Model::getDatatable();
}
  1. 为数据动作创建路由。
Route::get('/models/data', 'ModelController@data')->name('models.data');
  1. 在索引 blade 中创建表格。
<table id="models-table">
    <thead>
        <tr>
            @foreach($columns as $column)
                <th>@lang('models.'.$column['data'])</th>
            @endforeach
        </tr>
    </thead>
</table>
  1. 配置脚本。
@push('scripts')
<script id="script">
    $(function () {
        var table = $('#models-table').DataTable({
            serverSide: true,
            processing: true,
            responsive: true,
            order: [ [0, 'desc'] ],
            ajax: {
                url: 'models/data'
            },
            columns: @json($columns),
            pagingType: 'full_numbers'
        });
    });
</script>
@endpush

RequestQueryBuildable 如何工作?

RequestQueryBuildable 通过请求中的参数使 SQL 查询的行为。

  1. 使用由逗号分隔的 ?only 来过滤列,类似于 SQL 中的 'select'
query: only=field1;field2;field3...
  1. 使用带有键和值的 ?search 来应用 where 或 whereHas
query: ?search=key:value,key2:value2

class MyModel extends Model {
    public static function searchable() {
        return [
                'key' => 'operator',
                'key2' => 'operator',
               ];
    }
    // ...model
} 

在模型上定义需要可搜索的方法,并且关系通过点关系.列来识别

  1. 使用 ?operators 来动态更改搜索运算符
query: field1:operator1
  1. 使用 ?sort 来排序结果
query: ?sort=field:direction;field2:direction
  1. 使用 ?with 来通过逗号分隔加载关系数据
query: relation1;relation2;relation3...