Laravel:“强制”查询生成器返回空列表

时间:2020-01-31 18:02:05

标签: php laravel

我有这些路线:

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,它将退还所有用户支付的所有款项。

如果您点击/users/id/payments,则仅当condition为true时,它才应退还用户支付的所有款项,否则应返回一个空列表。

此代码有效,但是$query->whereNull('id');是一种实际上可以访问数据库的解决方法。

有什么方法可以避免访问数据库并仍然返回空列表?

预先感谢

2 个答案:

答案 0 :(得分:0)

您可以避免访问数据库,但仍使用以下命令返回空列表 初始化为空集合或数组的变量

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);
    }
}

答案 1 :(得分:0)

我试图在函数中返回一个单值,但是更容易遵循@Chin Leung给出的建议(谢谢!)

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));
    }
}