我有以下路线:
Route::apiResource('payments', 'PaymentController', ['except' => ['store', 'destroy']]);
Route::get('users/{user}/payments', [
'as' => 'users.payments',
'uses' => 'PaymentController@index',
]);
这个控制器:
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
$query->whereNull('id'); // <----- This hits the database
}
}
return PaymentResource::collection($query->paginate(10));
}
}
如果您点击它,则应返回所有用户进行的所有付款。/payments
如果命中它,则仅当为 true 时,它才应返回用户进行的所有付款,否则应返回空列表。/users/id/paymentscondition
此代码有效,但是是实际命中数据库的解决方法。$query->whereNull('id');
有没有办法避免命中数据库并仍然返回空列表?
猛跑小猪
缥缈止盈