2 回答

TA貢獻1858條經(jīng)驗 獲得超8個贊
您可以避免命中數(shù)據(jù)庫,但仍然使用初始化的變量返回空列表到空集合或數(shù)組
class PaymentController
{
public function index(Request $request, User $user)
{
// Initialize query builder
$query = Payment::query();
// If a user was provided, return all payments belonging to that user
// if condition is satisfied
$return = collect();
if ($user) {
if (condition) {
$return = $customer->payments()->paginate(10);
}
}
return PaymentResource::collection($return);
}
}

TA貢獻2041條經(jīng)驗 獲得超4個贊
我試圖在函數(shù)中有一個單一的返回,但更容易遵循@Chin梁給出的建議(謝謝!
class PaymentController
{
public function index(Request $request, User $user)
{
// Initialize query builder
$query = Payment::query();
// If a user was provided, return all payments belonging to that user
// if condition is satisfied
if ($user) {
if (condition) {
$query = $customer->payments();
} else {
// Some code that causes no results
return PaymentResource::collection(collect());
}
}
// Other code here, for example a where statement
// depending on what is passed in $request
return PaymentResource::collection($query->paginate(10));
}
}
- 2 回答
- 0 關(guān)注
- 122 瀏覽
添加回答
舉報