所以我在模型的许多部分都有相同的代码重复,但是在不同的函数中。这是一个例子:$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 回答
- 0 关注
- 86 浏览
添加回答
举报
0/150
提交
取消