亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Laravel:“強制”查詢生成器返回空列表

Laravel:“強制”查詢生成器返回空列表

PHP
30秒到達戰場 2022-09-03 16:01:17
我有以下路線: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');有沒有辦法避免命中數據庫并仍然返回空列表?
查看完整描述

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

    }

}


查看完整回答
反對 回復 2022-09-03
?
縹緲止盈

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

    }

}


查看完整回答
反對 回復 2022-09-03
  • 2 回答
  • 0 關注
  • 123 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號