为了账号安全,请及时绑定邮箱和手机立即绑定

代码重构 - 改进重复的查询生成器调用以提高可读性

代码重构 - 改进重复的查询生成器调用以提高可读性

PHP
MMMHUHU 2023-10-15 17:23:40
所以我在模型的许多部分都有相同的代码重复,但是在不同的函数中。这是一个例子:$records = AuditLogEntry::whereIn('context_type', ['Type1', 'Type2'])        ->whereContextId($this->id)        ->whereIn('event_type', [config('constants.audit_log.EVENT_TYPE_UPDATE'),            config('constants.audit_log.EVENT_TYPE_CANCEL')])        ->whereDate('created_at', '>', $date)        ->select(['id', 'meta', 'event_type'])        ->orderByDesc('created_at')        ->get();在另一个执行其他操作的函数中,我也有类似的代码块(注意最后 4 行代码):$records2 = AuditLogEntry::whereContextType('Type3')            ->whereEventType(config('constants.audit_log.EVENT_TYPE_EXERCISE'))            ->whereIn('context_id', $contexts->toArray())            ->whereDate('created_at', '>', $date)            ->select(['meta', 'event_type'])            ->orderByDesc('created_at')            ->get();所以我的想法只是对这些行进行简单的代码重构: ->whereDate('created_at', '>', $date)            ->select(['meta', 'event_type'])            ->orderByDesc('created_at')            ->get();因为我的模型中的许多地方都需要它们,所以我尝试使用回调来执行此代码重构,如下所示:private function recordsQuery(string $date): Closure{    return function ($query) use ($date) {        $query->whereDate('created_at', '>', $date)            ->select(['meta', 'event_type'])            ->orderByDesc('created_at')            ->get();    };}那么我可以删除这 4 行代码并得到如下所示的代码:$exercises = AuditLogEntry::whereContextType('Exercise')            ->whereEventType(config('constants.audit_log.EVENT_TYPE_EXERCISE'))            ->whereIn('context_id', $grantsExercised->pluck('id')->toArray())            ->$this->recordsQuery(); /** This is not working, obviously but you guys can get the idea of what I'm trying to do */所以问题是我想使用链接来提高可读性,我在想是否可以使用宏并扩展查询生成器,包括这个新函数。当然,我想听听大家的意见,看看是否有人有更好的主意。
查看完整描述

1 回答

?
慕勒3428872

TA贡献1848条经验 获得超6个赞

您可以创建查询范围来实现此目的:https ://laravel.com/docs/7.x/eloquent#local-scopes


查看完整回答
反对 回复 2023-10-15
  • 1 回答
  • 0 关注
  • 61 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信