问题描述
所以我在同一模型的许多部分重复了相同的代码,但是在不同的功能上重复了它。这是一个示例:
$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();
$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','event_type'])
->orderByDesc('created_at')
->get();
因为在我的模型的许多地方都需要它们,所以我试图使用回调来执行此代码重构,如下所示:
private function recordsQuery(string $date): Closure
{
return function ($query) use ($date) {
$query->whereDate('created_at','event_type'])
->orderByDesc('created_at')
->get();
};
}
$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 */
所以问题是我想使用链接来提高可读性,我在想是否可以使用宏并扩展包括此新功能的查询生成器。当然,我想听听您的意见,看看有人是否有更好的主意。
感谢您的帮助:)
解决方法
您可以通过查询范围来实现:https://laravel.com/docs/7.x/eloquent#local-scopes