第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

代碼重構(gòu) - 改進重復(fù)的查詢生成器調(diào)用以提高可讀性

代碼重構(gòu) - 改進重復(fù)的查詢生成器調(diào)用以提高可讀性

PHP
MMMHUHU 2023-10-15 17:23:40
所以我在模型的許多部分都有相同的代碼重復(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


查看完整回答
反對 回復(fù) 2023-10-15
  • 1 回答
  • 0 關(guān)注
  • 112 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號