2 回答
TA贡献1858条经验 获得超8个赞
您可以避免命中数据库,但仍然使用初始化的变量返回空列表到空集合或数组
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条经验 获得超4个赞
我试图在函数中有一个单一的返回,但更容易遵循@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 关注
- 88 浏览
添加回答
举报