我在 Larevel 中有一個模型,它采用參數(shù)來報(bào)告數(shù)據(jù)庫中的總單位。我希望能夠過濾返回的基礎(chǔ)上,各單位$entity_ids和$start與$end用戶選擇的日期。entity_ids使用簡單的whereIn()方法調(diào)用工作正常,但日期導(dǎo)致了一些問題。我在Order.php模型中的代碼如下:public static function getAllOrdersForReporting($entity_ids, $start, $end) { $orders = Order::select('all order information entered here') ->whereIn('orders.entity_id', $entity_ids) ->when($start && $end, function ($query, $start, $end) { //<-- Error Thrown Here return $query->whereBetween('order_date', [$start, $end]); }) ->join('entities', 'entities.id', '=', 'ura_orders.entity_id') ->join('entity_address_information', 'entity_address_information.entity_id', '=', 'ura_orders.entity_id')->distinct()->get(); return $orders;}在我的ReportingController.php我輸入以下內(nèi)容:public function displayUnits() { $entities = request()->entities_ids; $start = request()->start_date; $end = request()->end_date; $orders = Ura_order::getAllOrdersForReporting($entities, $start, $end); return view('reporting.pages.units', compact('entities', 'start', 'end', 'orders'));}但是,當(dāng)我運(yùn)行它時(shí),出現(xiàn)以下錯誤:函數(shù) App\Models\Order::App\Models{closure}() 的參數(shù)太少,2 傳入 C:\xampp\htdocs\mywebsite\vendor\laravel\framework\src\Illuminate\Database\Concerns\BuildsQueries.php在第 91 行,預(yù)期正好有 3 個不完全確定這個錯誤是什么意思,除了Model只看到 2 個傳入的錯誤,它預(yù)期 3 個。我在代碼中標(biāo)記了上面拋出錯誤的行。關(guān)于如何讓它發(fā)揮作用的任何建議?我知道 for 的第三個參數(shù)when()應(yīng)該是一個回調(diào)函數(shù),但不知道如何使它工作。
2 回答

慕慕森
TA貢獻(xiàn)1856條經(jīng)驗(yàn) 獲得超17個贊
您必須use在回調(diào)函數(shù)中使用變量:
->when($start && $end, function ($query) use ($start, $end) {
return $query->whereBetween('order_date', [$start, $end]);
})

揚(yáng)帆大魚
TA貢獻(xiàn)1799條經(jīng)驗(yàn) 獲得超9個贊
您可以嘗試使用以下代碼:
->when($start && $end, function ($query, $condition) use($start, $end) {
return $query->whereBetween('order_date', [$start, $end]);
})
正如評論中已經(jīng)指出的, a 的 tihrd 參數(shù)when()應(yīng)該是 a function,使用該use()語句您可以在閉包中傳遞變量。
- 2 回答
- 0 關(guān)注
- 358 瀏覽
添加回答
舉報(bào)
0/150
提交
取消