garkavenkov/selector-service

v0.7.0 2024-06-09 08:36 UTC

This package is auto-updated.

Last update: 2024-09-09 09:10:47 UTC


README

SelectorService - 从API选择日期的服务

安装

使用 Composer

composer require garkavenkov/selector-service

使用方法

初始化

在模型控制器中创建(如果方法已存在则添加)__construct。

use Garkavenkov\Laravel\SelectorService;

class [ControllerName] extends Controller
{
    protected $selector;

    public function __construct(SelectorService $selector)
    {
        $this->selector = $selector;
    }

    public function index()
    {
        $data = $this->selector->get([ModelClass]::class);

        return $data;
    }    

    ... 
}

在[ModelClass]中添加包含模型允许的字段以进行数据选择的受保护静态数组及函数

class [ModelClass] extends Model
{
    use HasFactory;

    protected static $filterable = [
        'id',
        'name',
        ...

    ];

    ...

    public static function getFilterableFields()
    {
        return self::$filterable;
    }
}

所有条件通过查询字符串传递

where

例如

https://:8000/api/people?where=name=John

返回表中字段 name 的值为 John 的记录

也可以选择满足多个条件的数据

https://:8000/api/people?where=name=John;age=20

返回表中 John 年龄为 20 的记录

per_page

对于分页数据,传递 per_page 参数,包含每页的记录数

https://:8000/api/people?per_page=10

返回前10条记录

page

如果已发送 per_page 参数,也可以传递 page 参数。

https://:8000/api/people?per_page=10&page=2

返回从 1120 的记录

with

如果模型有关系,可以返回带有关系数据的记录。

例如

模型 Person 有关系 address

https://:8000/api/people?where=name=John&with=address

返回带有关系的 Person 集合

也可以使用多个关系

https://:8000/api/people?where=name=John&with=address,hobbies

sort

为了对结果进行排序,添加参数 sort

https://:8000/api/people?where=name=John&with=address&sort=age

结果将按照字段 age 的升序排序。如果要进行降序排序,在字段名前使用符号 -

https://:8000/api/people?where=name=John&with=address&sort=-age

也可以对多个字段进行排序

https://:8000/api/people?where=name=John&sort=-age,hight

scope

也可以使用范围选择数据

https://:8000/api/people?where=name=John&scope=programmer

返回所有范围为 programmer 的 person 以及名为 John 的人

当然,也可以使用多个范围

https://:8000/api/people?where=name=John&scope=programmer,php

random

https://:8000/api/people?random=N

返回 N 条随机记录

fields

可以选择记录的特定字段

https://:8000/api/people?where=name=John&fields=id,name,age

只返回字段 idnameage