所以我在模型的許多部分都有相同的代碼重復(fù),但是在不同的函數(shù)中。這是一個例子:$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();在另一個執(zhí)行其他操作的函數(shù)中,我也有類似的代碼塊(注意最后 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();所以我的想法只是對這些行進行簡單的代碼重構(gòu): ->whereDate('created_at', '>', $date) ->select(['meta', 'event_type']) ->orderByDesc('created_at') ->get();因為我的模型中的許多地方都需要它們,所以我嘗試使用回調(diào)來執(zhí)行此代碼重構(gòu),如下所示: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 */所以問題是我想使用鏈接來提高可讀性,我在想是否可以使用宏并擴展查詢生成器,包括這個新函數(shù)。當然,我想聽聽大家的意見,看看是否有人有更好的主意。
1 回答

慕勒3428872
TA貢獻1848條經(jīng)驗 獲得超6個贊
您可以創(chuàng)建查詢范圍來實現(xiàn)此目的:https ://laravel.com/docs/7.x/eloquent#local-scopes
- 1 回答
- 0 關(guān)注
- 112 瀏覽
添加回答
舉報
0/150
提交
取消