编程

[Laravel 扩展包] Laravel 模型日期作用域

912 2023-05-13 17:52:00

Laravel Date Scopes 包为 Laravel Eloquent 模型提供了一些有用的查询作用域。受到 Livewire 作者 Caleb Porzio 的启发:

Would be rad if Eloquent had these, yeah? pic.twitter.com/qjOD5vv68y

— Caleb Porzio (@calebporzio) April 7, 2023

在模型中添加 DateScopes trait,示例:

use LaracraftTech\LaravelDateScopes\DateScopes;
 
class Transaction extends Model
{
    use DateScopes;
}

这样就获得了许多基于时间的 scope。下面的例子是各种 hour 类型的 scope,同样类似的有 seconds, days, weeks, months, year, decade 等等:

// query transactions created during the last hour
Transaction::ofLastHour();
 
// query transactions created during the last 6 hours
Transaction::ofLast6Hours();
 
// query transactions created during the last 12 hours
Transaction::ofLast12Hours();
 
// query transactions created during the last 18 hours
Transaction::ofLast18Hours();
 
// query transactions created during the last 24 hours
Transaction::ofLast24Hours();
 
// query transactions created during the last N hours
Transaction::ofLastHours(48);

下面的例子展示了如何使用  lastYear() 查询作用域获取去年的所有交易信息:

 $transactions = Transaction::lastYear()->get();

更多详情,可查看其 GITHUB 仓库