赵思远 / laravel-lookupable
适用于 Laravel Eloquent 模型的 Lookupable 特性,实现快速高效的表查询。
0.1.3
2019-08-19 13:56 UTC
Requires
- php: >=7.0
- illuminate/database: 5.5.x|5.6.x|5.7.x|5.8.x
This package is auto-updated.
Last update: 2024-09-20 01:41:56 UTC
README
适用于 Laravel Eloquent 模型的 Lookupable 特性,实现快速高效的表查询。
需要 Laravel 5.5 或更高版本!
关于此包
当构建更复杂的应用程序时,查询可能会累积而不自知。Lookupable 特性将仅在请求期间获取查询实例一次并将其存储在内存中。每次您想要查找同一模型的 Lookupable 实例时,查找方法将访问内存中存储的实例并防止查询。
示例:您有一个用于状态如 pending
、draft
、published
、deleted
的查找表。您可以多次访问这些实例,但每个请求中只有一个查询。
$draftStatus = Status::lookup('draft'); // Executes the select * query and puts all instances in memory $publishedStatus = Status::lookup('published'); // Will get the instance from memory $deletedStatus = Status::lookup('deleted'); // Will get the instance from memory
安装
您可以通过 composer 安装此包
composer require pascalvgemert/laravel-lookup
用法
仅适用于 Eloquent 模型的 Lookupable
特性
class Role extends \Illuminate\Database\Eloquent\Model { use Lookupable/Lookupable; }
“Roles” 表的示例表结构
查找方法
之后,您可以使用以下方法轻松查找实例:
单次查找
/** @var \App\Models\Role|null **/
$role = Role::lookup('admin');
单次查找,如果没有找到记录将抛出 \Illuminate\Database\Eloquent\ModelNotFoundException 错误
/** @var \App\Models\Role **/
$role = Role::lookupOrFail('admin');
多次查找
/** @var \Illuminate\Database\Eloquent\Collection **/
$roles = Role::lookupMany(['admin', 'guest']);
多次查找,如果给定的任何记录找不到,将抛出 \Illuminate\Database\Eloquent\ModelNotFoundException 错误
/** @var \Illuminate\Database\Eloquent\Collection **/
$roles = Role::lookupManyOrFail(['admin', 'guest']);
软删除项
上述所有方法都可以接受第二个参数(bool $withTrashed = false;
),以返回包含软删除项的结果。
注意:当尝试使用软删除项时,请确保您的 Eloquent 模型实现了 \Illuminate\Database\Eloquent\SoftDeletes 特性。
我没有 identifier
列?
因此,您的数据库表不包含 identifier
列,例如这样的 Country
表
不用担心,您可以在模型中定义自己的查找列名,如下所示
class Country extends \Illuminate\Database\Eloquent\Model { use Lookupable/Lookupable; protected $lookupColumn = 'code'; }
鸣谢
- 赵思远
- Kevin op den Kamp(提供灵感)
- Startselect